/* Copyright 2020,2022-2024 NXP
 *
 * NXP Confidential. This software is owned or controlled by NXP and may only
 * be used strictly in accordance with the applicable license terms.  By
 * expressly accepting such terms or by downloading, installing, activating
 * and/or otherwise using the software, you are agreeing that you have read,
 * and that you agree to comply with and are bound by, such license terms.  If
 * you do not agree to be bound by the applicable license terms, then you may
 * not retain, install, activate or otherwise use the software.
 */

#include "phUwb_BuildConfig.h"
#if !defined(UWBIOT_APP_BUILD__DEMO_PNP)
#include "UWBIOT_APP_BUILD.h"
#endif

#if defined(UWBIOT_APP_BUILD__DEMO_PNP)

#include <stdio.h>
#include "board.h"


#include "UWBT_PowerMode.h"
#include "fsl_component_led.h"
#include "UWB_Spi_Driver_Interface.h"
#include "UWB_Evt_Pnp.h"
#include "Uwb_Read_task.h"
//#include "peripherals.h"
#include "UwbPnpInternal.h"
#include "phOsalUwb.h"
#include "phUwbTypes.h"
#include "UWB_DRIVER.h"
#include "phTmlUwb_transport.h"
#include "uwbiot_ver.h"
#include "UwbApi_Utility.h"
#include "fsl_adapter_flash.h"
#include "fwk_platform_definitions.h"
#include "fsl_lpuart.h"
#include "fsl_common.h"
#include "fsl_port.h"
#include "fsl_gpio.h"
#include "OtaSupport.h"
#include "fwk_platform_extflash.h"
#include "OtaPrivate.h"
#include "fsl_adapter_reset.h"
#include "RNG_Interface.h"
#include "SecLib.h"

#include "fsl_cmc.h"
#include "fsl_spc.h"
#include "sleep_app.h"
#include "fsl_vbat.h"
#include "FunctionLib.h"


#define HIF_TASK_PRIO        3
#define PNP_APP_TASK_PRIO    3
#define UCI_READER_TASK_PRIO 3
#define HIF_WRITER_TASK_PRIO 2
#define HIF_RESET_TASK_PRIO  1
#define IFR_SIZE_1			 8192
#define IFR_SIZE			 2048
#define PACKET_HEADER 0xEF01
const uint32_t MACAdrss = 0x12002000;
const uint32_t startAdrss = 0x12002000;
const uint32_t CFO_Adrss = 0x12002040;
const uint32_t POW_Adrss = 0x12002080;
const uint32_t IDEN_Adrss = 0x120020C0;
const uint32_t QRCODE_Adrss = 0x12002100;
const uint32_t TWR_Adrss = 0x12002200;
const uint32_t PDOA_Adrss = 0x12002300;

const uint32_t ROOT_CA_CERT_Adrss = 0x12002400;
const uint32_t LOCK_CERT_Adrss = 0x12002760;
const uint32_t LOCK_KEY_Adrss = 0x12002AC0;
const uint32_t BLE_BROADCAST_KEY_Adrss = 0x12002BC0;

uint8_t uid_32bytes[32] = {0};

UWBOSAL_TASK_HANDLE mHifTask;
UWBOSAL_TASK_HANDLE mPnpAppTask;
UWBOSAL_TASK_HANDLE mUciReaderTask;
UWBOSAL_TASK_HANDLE mHifWriterTask;
UWBOSAL_TASK_HANDLE mHifResetTask;
void *mUartWriteMutex = NULL;
void *mHifWriteMutex = NULL;
void *mHifSyncMutex  = NULL;
intptr_t mHifWriteQueue;
void *mHifIsr_Sem = NULL;
static uint8_t mRxData[UWB_MAX_HELIOS_RSP_SIZE];
static uint8_t mTlvBuf[TLV_RESP_SIZE];
uint32_t s_buff[IFR_SIZE];
static uint8_t AES_Key[16];

uint8_t rootcert_data[864] = {0};
uint8_t  rootcert_data_encrypt[864] = {0};
uint8_t rootcertdata_sbf[864] = {0};
uint8_t rootcertdata_sbfdecrypt[864] = {0};//用于存放flash中解密后的data
uint8_t rootcert_data1[864] = {0}; //用于存放发送的data
uint8_t rootcertdata_tlv[864] = {0}; //用于存放加密后的data

uint8_t lockcert_data[864] = {0};
uint8_t  lockcert_data_encrypt[864] = {0};
uint8_t lockcertdata_sbf[864] = {0};
uint8_t lockcertdata_sbfdecrypt[864] = {0};//用于存放flash中解密后的data
uint8_t lockcert_data1[864] = {0}; //用于存放发送的data
uint8_t lockcertdata_tlv[864] = {0}; //用于存放加密后的data

uint8_t lockkey_data[256] = {0};
uint8_t  lockkey_data_encrypt[256] = {0};
uint8_t lockkeydata_sbf[256] = {0};
uint8_t lockkeydata_sbfdecrypt[256] = {0};//用于存放flash中解密后的data
uint8_t lockkey_data1[256] = {0}; //用于存放发送的data
uint8_t lockkeydata_tlv[256] = {0}; //用于存放加密后的data

uint8_t s_buffer_rootcacert[864];
uint8_t s_buffer_rootcacertDecrypt[864]; //解密后的数据

uint8_t s_buffer_lockcert[864];
uint8_t s_buffer_lockcertDecrypt[864]; //解密后的数据

uint8_t s_buffer_lockkey[256];
uint8_t s_buffer_lockkeyDecrypt[256]; //解密后的数据
uint8_t flash_buf[PLATFORM_EXTFLASH_PAGE_SIZE] = {0};

uint8_t uwb_ota_init = 0;

/* Allocate the memory for the heap. */
//uint8_t __attribute__((section(".bss.$SRAM1"))) ucHeap[configTOTAL_HEAP_SIZE];

/*! *********************************************************************************
 * \brief  Computes the CRC for the hardware parameters and stores it
 *
 * \param[in] pHwParams  pointer to a structure containing HW parameters
 *
 * \return Computed CRC value.
 *
 ********************************************************************************** */
#define POLGEN 0x1021U
static uint16_t NV_ComputeCrc(uint8_t *ptr, uint32_t len)
{
    uint16_t computedCRC = 0U;

    for (uint32_t i = 0U; i < len; i++)
    {
        uint8_t byte;
        byte = ptr[i];
        computedCRC ^= ((uint16_t)byte << 8U);
        for (uint8_t crcA = 8U; crcA != 0U; crcA--)
        {
            if ((computedCRC & 0x8000U) != 0U)
            {
                computedCRC <<= 1U;
                computedCRC ^= POLGEN;
            }
            else
            {
                computedCRC <<= 1U;
            }
        }
    }
    return computedCRC;
}

static uint32_t swap_bytes_32(uint32_t value)
{
	 return ((value & 0x000000FF) << 24) |
	        ((value & 0x0000FF00) << 8) |
	        ((value & 0x00FF0000) >> 8) |
	        ((value & 0xFF000000) >> 24);
}

static uint32_t g_ota_file_len = 0u;

static void UWB_Respond_cmd(uint8_t cmd,  uint8_t status)
{
	uint8_t respondCmd[4] = {0};
	respondCmd[0] = cmd;
	respondCmd[1] = 0x00;
	respondCmd[2] = 0x01;
	respondCmd[3] = (status & 0xff);
    (void)phOsalUwb_LockMutex(mUartWriteMutex);
	UWB_Hif_SendRsp(respondCmd, 4);
    (void)phOsalUwb_UnlockMutex(mUartWriteMutex);
}

static void APP_SetCMCConfiguration(void)
{
    CMC_SetPowerModeProtection(APP_CMC, kCMC_AllowAllLowPowerModes);
    CMC_LockPowerModeProtectionSetting(APP_CMC);
    CMC_EnableDebugOperation(APP_CMC, false);
    CMC_ConfigFlashMode(APP_CMC, false, true, false);
}

static void APP_DeInitVbat(void)
{
    VBAT_EnableBackupSRAMRegulator(APP_VBAT, false);
    VBAT_EnableFRO16k(APP_VBAT, false);
    while (VBAT_CheckFRO16kEnabled(APP_VBAT))
        ;
    VBAT_EnableBandgap(APP_VBAT, false);
    while (VBAT_CheckBandgapEnabled(APP_VBAT))
        ;
}

static void APP_EnterDeepSleep1Mode(void)
{
    cmc_power_domain_config_t config;

    /* Enable CORE VDD Voltage scaling. */
    SPC_EnableLowPowerModeCoreVDDInternalVoltageScaling(APP_SPC, true);

    /* Set NBU into Deep Sleep Mode */
    RFMC->RF2P4GHZ_CTRL = (RFMC->RF2P4GHZ_CTRL & (~RFMC_RF2P4GHZ_CTRL_LP_MODE_MASK)) | RFMC_RF2P4GHZ_CTRL_LP_MODE(0x3);
    RFMC->RF2P4GHZ_CTRL |= RFMC_RF2P4GHZ_CTRL_LP_ENTER_MASK;

    /* Set MAIN_CORE and MAIN_WAKE power domain into Deep Sleep Mode. */
    config.clock_mode  = kCMC_GateAllSystemClocksEnterLowPowerMode;
    config.main_domain = kCMC_DeepSleepMode;
    config.wake_domain = kCMC_DeepSleepMode;

    CMC_EnterLowPowerMode(APP_CMC, &config);
}

/*USB header is handled here as per designed doc*/
void UWB_Handle_SR1XXT_TLV(tlv_t *tlv)
{
    switch (tlv->type) {
    case UCI_CMD: {
    	PRINTF("UCI_CMD;\r\n");
#if (ENABLE_UCI_CMD_LOGGING == ENABLED)
        PRINTF("UCI cmd:");
        for (int i = 0; i < tlv->size; i++) {
            PRINTF(" %02x", tlv->value[i]);
        }
        PRINTF("\n");
#endif
        uint8_t mt = (*(tlv->value) & UCI_MT_MASK) >> UCI_MT_SHIFT;
        if (mt == MT_ESE_CTRL_CMD) {
            size_t rspSize = 0xFFFF; /* Max allowed APDU response size  */
#if (UWBFTR_SE_SE051W || UWBFTR_SE_SN110)
            Se_Transceive(tlv->value, tlv->size, mTlvBuf, &rspSize);
            UWB_Hif_SendRsp(mTlvBuf, rspSize);

#else
            rspSize    = 0x05;
            mTlvBuf[0] = MT_ESE_CTRL_RSP << UCI_MT_SHIFT | 0;
            mTlvBuf[1] = 0x00;
            mTlvBuf[2] = 0x01;
            mTlvBuf[3] = 0x00;
            mTlvBuf[4] = 0x01; // STATUS_REJECTED
            UWB_Hif_SendRsp(mTlvBuf, rspSize);
#endif
        }
        else {
            if (UWB_SpiUciWrite(tlv->value, tlv->size) != kUWBSTATUS_SUCCESS) {
                PRINTF("ERROR: error processing UCI command\n");
            }
        }
    } break;

    case HBCI_CMD: {
    	PRINTF("HBCI_CMD;\r\n");
        size_t rspLen = UWB_MAX_HELIOS_RSP_SIZE;
#if (ENABLE_UCI_CMD_LOGGING == ENABLED)
        PRINTF("HBCI cmd:");
        for (uint16_t i = 0; i < tlv->size; i++) {
            PRINTF(" %02x", tlv->value[i]);
        }
        PRINTF("\n");
#endif

        if (kUWBSTATUS_SUCCESS == UWB_SpiHbciXfer(tlv->value, tlv->size, mRxData, &rspLen)) {
            UWB_Hif_SendRsp(mRxData, rspLen);
        }
        else {
            PRINTF("ERROR: error processing UCI command\n");
        }
    } break;

    case HBCI_QUERY_CMD: {
    	PRINTF("HBCI_QUERY_CMD;\r\n");
#if (ENABLE_UCI_CMD_LOGGING == ENABLED)
        PRINTF("HBCI Query cmd:");
        for (int i = 1; i < tlv->size; i++) {
            PRINTF(" %02x", tlv->value[i]);
        }
        PRINTF("\n");
#endif
        uint8_t readLen = tlv->value[0];
        if (kUWBSTATUS_SUCCESS == UWB_SpiHbciXferWithLen(&tlv->value[1], (tlv->size - 1), mRxData, readLen)) {
            if (readLen > 0) {
                UWB_Hif_SendRsp(mRxData, readLen);
            }
        }
        else {
            PRINTF("ERROR: error processing UCI command\n");
        }
    } break;

    case HBCI_LAST_CMD: {
    	PRINTF("HBCI_LAST_CMD;\r\n");
        size_t rspLen = UWB_MAX_HELIOS_RSP_SIZE;
#if (ENABLE_UCI_CMD_LOGGING == ENABLED)
        PRINTF("HBCI Last cmd:");
        for (int i = 0; i < tlv->size; i++) {
            PRINTF(" %02x", tlv->value[i]);
        }
        PRINTF("\n");
#endif
        /* For the query command after HBCI image DND, host needs to wait till IRQ is received from Helios */
        if (!UWB_Uwbs_Interupt_Status()) {
            phOsalUwb_Delay(100);
        }
        if (kUWBSTATUS_SUCCESS == UWB_SpiHbciXfer(tlv->value, tlv->size, mRxData, &rspLen)) {
            UWB_Hif_SendRsp(mRxData, rspLen);
        }
        else {
            PRINTF("ERROR: error processing UCI command\n");
        }
        /*After Query command Spurious Interrupt is expected, Add 100msec delay before resuming UCI UCI read task*/
        phOsalUwb_Delay(10);
        /* Set back tml transfer mode to uci before resuming the tml reader task */
        UWB_Tml_Set_Mode(kUWB_UWBS_TML_MODE_UCI);
        /* After HBCI DND resume UCI mode by resuming tasks required for UCI*/
        phOsalUwb_TaskResume(mUciReaderTask);
        phOsalUwb_TaskResume(mHifWriterTask);
        UWB_Uwbs_Enable_Interrupt();
    } break;
    case RESET: {
    	PRINTF("RESET;\r\n");
        PRINTF_WITH_TIME("Reset Received\n");
        /*Acquire mReadTaskSyncMutex to make sure there is no pending
         * operation in the read task and then suspend read task*/
        //(void)phOsalUwb_LockMutex(mReadTaskSyncMutex);
        // PRINTF_WITH_TIME("After mReadTaskSyncMutex\n");
        /*Acquire mUsbSyncMutex to make sure there is no pending
         * operation in the mUsbWriterTask task and then suspend mUsbWriterTask task*/
        (void)phOsalUwb_LockMutex(mHifSyncMutex);
        PRINTF_WITH_TIME("After mUsbSyncMutex\n");
        phOsalUwb_TaskSuspend(mUciReaderTask);
        phOsalUwb_TaskSuspend(mHifWriterTask);

        /*Delete all the elements from the USB Write Queue before going in to Bootrom mode*/
        int itemsInQueue = (WRITER_QUEUE_SIZE - phOsalUwb_queueSpacesAvailable(mHifWriteQueue));
        PRINTF_WITH_TIME("items in Queue : %d\n", itemsInQueue);
        for (int i = 0; i < itemsInQueue; i++) {
            phLibUwb_Message_t tlv;
            if (phOsalUwb_msgrcv(mHifWriteQueue, &tlv, NO_DELAY) == UWBSTATUS_FAILED) {
                PRINTF("Failed to Receive an item\n");
                continue;
            }
            if (tlv.pMsgData != NULL) {
                phOsalUwb_FreeMemory(tlv.pMsgData);
                tlv.pMsgData = NULL;
                PRINTF("FREE\r\n");
            }
        }
        PRINTF_WITH_TIME("Chip Enable Started\n");
        // Assert/deassert pin
        UWB_Tml_Io_Set(kUWBS_IO_O_ENABLE_HELIOS, 0);
        UWB_Tml_Io_Set(kUWBS_IO_O_HELIOS_RTC_SYNC, 0);
        phOsalUwb_Delay(5);
        UWB_Tml_Io_Set(kUWBS_IO_O_ENABLE_HELIOS, 1);
        UWB_Tml_Io_Set(kUWBS_IO_O_HELIOS_RTC_SYNC, 1);
        phOsalUwb_Delay(50);
        PRINTF_WITH_TIME("Chip Enable Completed\n");
        (void)phOsalUwb_UnlockMutex(mHifSyncMutex);
        //(void)phOsalUwb_UnlockMutex(mReadTaskSyncMutex);
        mTlvBuf[0] = 0x01;
        mTlvBuf[1] = 0x02;
        mTlvBuf[2] = 0x03;
        mTlvBuf[3] = 0x04;
        /* set HBCI MODE */
        UWB_Tml_Set_Mode(kUWB_UWBS_TML_MODE_HBCI);
        // Send response over USB to HOST upper layer
        UWB_Hif_SendRsp(mTlvBuf, RESET_RESPONSE_SIZE);
    } break;
    case GET_SOFTWARE_VERSION: {
        mTlvBuf[0] = GET_SOFTWARE_VERSION;
        mTlvBuf[1] = 0x02;
        mTlvBuf[2] = UWBIOTVER_STR_VER_MAJOR;
        mTlvBuf[3] = UWBIOTVER_STR_VER_MINOR;
        UWB_Hif_SendRsp(mTlvBuf, GET_SOFTWARE_VERSION_RESPONSE_SIZE);
    } break;
    case GET_BOARD_ID: {
        uint8_t len = 0;
        mTlvBuf[0]  = GET_BOARD_ID;
        mTlvBuf[1]  = 0x10;
        BOARD_GetMCUUid(&mTlvBuf[2], &len);
        UWB_Hif_SendRsp(mTlvBuf, (uint16_t)(len + 2));
    } break;
    case MCU_RESET: {
        PRINTF("Issuing NVIC_SystemReset, MCU going to reboot!\n");
        NVIC_SystemReset(); // No prints after this line wont appear
    } break;
    case USB_LOOPBACK: { // echo back to usb
        UWB_Hif_SendRsp(tlv->value - 3, (uint16_t)tlv->size + 3);
    } break;
    case GET_BOARD_VERSION: {
        mTlvBuf[0] = UWB_BOARD_VERSION;
        UWB_Hif_SendRsp(mTlvBuf, 1);
    } break;
    case GET_VERISON_INFO: {
        size_t rspSize = UWBPnP_GetVersionInfo(mTlvBuf, sizeof(mTlvBuf), kUBWPnPBoardIdentifier_SR1XX_RV4);
        UWB_Hif_SendRsp(mTlvBuf, rspSize);
    } break;
    case CHIPID_CMD:{
    	MSCM_Type *mscm = (MSCM_Type *)MSCM_BASE;
    	uint32_t uid[4];
        for(int i=0;i<4;i++)
        {
        	uid[i] = __builtin_bswap32(mscm->UID[i]); // 将每个32位整数转换为大端序
        }
        mTlvBuf[0] = CHIPID_CMD;
        mTlvBuf[1] = 0x10;
        memcpy(&mTlvBuf[2], uid, 16);
        UWB_Hif_SendRsp(mTlvBuf, GET_CHIPID_SIZE);
    }break;
    case MACREAD_CMD:{
    	uint8_t s_buffer[16];
    	uint8_t s_buffer_Decrypt[16]; //解密后的数据
    	memset(s_buff, 0xFF, 16);
		for(uint8_t i = 0; i<16 ;i++)
		{
			s_buffer[i] = *(volatile uint8_t *)(MACAdrss + i);
		}

		AES_128_ECB_Decrypt(s_buffer,16,AES_Key,s_buffer_Decrypt);
        mTlvBuf[0] = MACREAD_CMD;
        mTlvBuf[1] = 0x10;
		memcpy(&mTlvBuf[2], s_buffer_Decrypt, 16);  // 复制MAC地址到数据区
		UWB_Hif_SendRsp(mTlvBuf, 18);
    }break;
    case IOTESTH_CMD:{
    	PRINTF("IOTESTH_CMD\r\n");
    	vTaskDelay(5);
    	GPIO_PinWrite(WAK15_GPIO,GPIO_PIN_WAK15,1);
    	GPIO_PinWrite(WAK4_GPIO,GPIO_PIN_WAK4,1);
        mTlvBuf[0] = IOTESTH_CMD;
        mTlvBuf[1] = 0x01;
        mTlvBuf[2] = 0x01;
        UWB_Hif_SendRsp(mTlvBuf, 3);
    }break;
    case IOTESTL_CMD:{
    	PRINTF("IOTESTL_CMD\r\n");
    	vTaskDelay(5);
    	GPIO_PinWrite(WAK15_GPIO,GPIO_PIN_WAK15,0);
    	GPIO_PinWrite(WAK4_GPIO,GPIO_PIN_WAK4,0);
        mTlvBuf[0] = IOTESTL_CMD;
        mTlvBuf[1] = 0x01;
        mTlvBuf[2] = 0x01;
        UWB_Hif_SendRsp(mTlvBuf, 3);
    }break;
    case CFOREAD_CMD:{
    	uint8_t s_buffer[16];
    	uint8_t s_buffer_Decrypt[16]; //解密后的数据
    	memset(s_buff, 0xFF, 16);
		for(uint8_t i = 0; i<16 ;i++)
		{
			s_buffer[i] = *(volatile uint8_t *)(CFO_Adrss + i);
		}

		AES_128_ECB_Decrypt(s_buffer,16,AES_Key,s_buffer_Decrypt);
        mTlvBuf[0] = CFOREAD_CMD;
        mTlvBuf[1] = 0x10;
		memcpy(&mTlvBuf[2], s_buffer_Decrypt, 16);  // 复制CFO校准值到数据区
		UWB_Hif_SendRsp(mTlvBuf, 18);
    }break;
    case POWREAD_CMD:{
    	uint8_t s_buffer[16];
    	uint8_t s_buffer_Decrypt[16]; //解密后的数据
    	memset(s_buff, 0xFF, 16);
		for(uint8_t i = 0; i<16 ;i++)
		{
			s_buffer[i] = *(volatile uint8_t *)(POW_Adrss + i);
		}

		AES_128_ECB_Decrypt(s_buffer,16,AES_Key,s_buffer_Decrypt);
        mTlvBuf[0] = POWREAD_CMD;
        mTlvBuf[1] = 0x10;
		memcpy(&mTlvBuf[2], s_buffer_Decrypt, 16);  // 复制POW校准值到数据区
		UWB_Hif_SendRsp(mTlvBuf, 18);
    }break;
    case IDENREAD_CMD:{
    	uint8_t s_buffer[16];
    	uint8_t s_buffer_Decrypt[16]; //解密后的数据
    	memset(s_buff, 0xFF, 16);
		for(uint8_t i = 0; i<16 ;i++)
		{
			s_buffer[i] = *(volatile uint8_t *)(IDEN_Adrss + i);
		}

		AES_128_ECB_Decrypt(s_buffer,16,AES_Key,s_buffer_Decrypt);
        mTlvBuf[0] = IDENREAD_CMD;
        mTlvBuf[1] = 0x10;
		memcpy(&mTlvBuf[2], s_buffer_Decrypt, 16);  // 复制IDEN值到数据区
		UWB_Hif_SendRsp(mTlvBuf, 18);
    }break;
    case QRCODEREAD_CMD:{
    	uint8_t s_buffer[64];
    	uint8_t s_buffer_Decrypt[64]; //解密后的数据
    	memset(s_buff, 0xFF, 64);
		for(uint8_t i = 0; i<64 ;i++)
		{
			s_buffer[i] = *(volatile uint8_t *)(QRCODE_Adrss + i);
		}

		AES_128_ECB_Decrypt(s_buffer,64,AES_Key,s_buffer_Decrypt);
        mTlvBuf[0] = QRCODEREAD_CMD;
        mTlvBuf[1] = 0x40;
		memcpy(&mTlvBuf[2], s_buffer_Decrypt, 64);  // 复制QRCODE值到数据区
		UWB_Hif_SendRsp(mTlvBuf, 66);
    }break;
    case TWRREAD_CMD:{
    	uint8_t s_buffer[64];
    	uint8_t s_buffer_Decrypt[64]; //解密后的数据
    	memset(s_buff, 0xFF, 64);
		for(uint8_t i = 0; i<64 ;i++)
		{
			s_buffer[i] = *(volatile uint8_t *)(TWR_Adrss + i);
		}

		AES_128_ECB_Decrypt(s_buffer,64,AES_Key,s_buffer_Decrypt);
        mTlvBuf[0] = TWRREAD_CMD;
        mTlvBuf[1] = 0x40;
		memcpy(&mTlvBuf[2], s_buffer_Decrypt, 64);  // 复制TWR校准值到数据区
		UWB_Hif_SendRsp(mTlvBuf, 66);
    }break;
    case PDOAREAD_CMD:{
    	uint8_t s_buffer[64];
    	uint8_t s_buffer_Decrypt[64]; //解密后的数据
    	memset(s_buff, 0xFF, 64);
		for(uint8_t i = 0; i<64 ;i++)
		{
			s_buffer[i] = *(volatile uint8_t *)(PDOA_Adrss + i);
		}

		AES_128_ECB_Decrypt(s_buffer,64,AES_Key,s_buffer_Decrypt);
        mTlvBuf[0] = PDOAREAD_CMD;
        mTlvBuf[1] = 0x40;
		memcpy(&mTlvBuf[2], s_buffer_Decrypt, 64);  // 复制PDOA校准值到数据区
		UWB_Hif_SendRsp(mTlvBuf, 66);
    }break;
    case ROOT_CACERTREAD:{
    	memset(s_buffer_rootcacert, 0xFF, 864);
		HAL_FlashRead(ROOT_CA_CERT_Adrss,864,s_buffer_rootcacert);
		AES_128_ECB_Decrypt(s_buffer_rootcacert,864,AES_Key,s_buffer_rootcacertDecrypt);
        mTlvBuf[0] = ROOT_CACERTREAD;
        mTlvBuf[1] = 0xCE;
		memcpy(&mTlvBuf[2], s_buffer_rootcacertDecrypt, 864);  // 复制ROOT_CACERT值到数据区
		UWB_Hif_SendRsp(mTlvBuf, 866);
    }break;
    case LOCK_CERTREAD:{
    	memset(s_buffer_lockcert, 0xFF, 864);
		HAL_FlashRead(LOCK_CERT_Adrss,864,s_buffer_lockcert);
		AES_128_ECB_Decrypt(s_buffer_lockcert,864,AES_Key,s_buffer_lockcertDecrypt);
        mTlvBuf[0] = LOCK_CERTREAD;
        mTlvBuf[1] = 0xCE;
		memcpy(&mTlvBuf[2], s_buffer_lockcertDecrypt, 864);  // 复制LOCK_CACERT值到数据区
		UWB_Hif_SendRsp(mTlvBuf, 866);
    }break;
    case LOCK_KEYREAD:{
    	memset(s_buffer_lockkey, 0xFF, 256);
		HAL_FlashRead(LOCK_KEY_Adrss,256,s_buffer_lockkey);
		AES_128_ECB_Decrypt(s_buffer_lockkey,256,AES_Key,s_buffer_lockkeyDecrypt);
        mTlvBuf[0] = LOCK_KEYREAD;
        mTlvBuf[1] = 0xEE;
		memcpy(&mTlvBuf[2], s_buffer_lockkeyDecrypt, 256);  // 复制LOCK_KEY值到数据区
		UWB_Hif_SendRsp(mTlvBuf, 258);
    }break;
    case BLE_BROADCAST_KEYREAD:{
    	uint8_t s_buffer[64];
    	uint8_t s_buffer_Decrypt[64]; //解密后的数据
    	memset(s_buff, 0xFF, 64);
		for(uint8_t i = 0; i<64 ;i++)
		{
			s_buffer[i] = *(volatile uint8_t *)(BLE_BROADCAST_KEY_Adrss + i);
		}

		AES_128_ECB_Decrypt(s_buffer,64,AES_Key,s_buffer_Decrypt);
        mTlvBuf[0] = BLE_BROADCAST_KEYREAD;
        mTlvBuf[1] = 0x40;
		memcpy(&mTlvBuf[2], s_buffer_Decrypt, 64);  // 复制PDOA校准值到数据区
		UWB_Hif_SendRsp(mTlvBuf, 66);
    }break;
    case CFO_CALIB:{
    	hal_flash_status_t status = 0;
    	memset(s_buff, 0xFF, PLATFORM_INTFLASH_SECTOR_SIZE);
    	status = HAL_FlashVerifyErase(CFO_Adrss, 0x40u, kHAL_Flash_MarginValueNormal);
    	uint8_t cfo_data[16] = {0};
    	memset(cfo_data, 0xFF, 16);
    	// 设置包头（大端序）
    	cfo_data[0] = (PACKET_HEADER >> 8) & 0xFF;  // 0xEF
    	cfo_data[1] = PACKET_HEADER & 0xFF;         // 0x01

    	if(status == kStatus_HAL_Flash_Success && tlv->size <= (sizeof(cfo_data) - 4))
    	{
    		memcpy(&cfo_data[2], tlv->value, tlv->size);
    		uint16_t  crc = NV_ComputeCrc(cfo_data,12);
    		uint8_t  cfo_data_encrypt[16] = {0};
    		PRINTF("NV_ComputeCrc = %04X\r\n",crc);
    		cfo_data[12] = ( crc >> 8) & 0xFF;
    		cfo_data[13] = crc & 0xFF;
    		AES_128_ECB_Encrypt(cfo_data,16,AES_Key,cfo_data_encrypt);
    		HAL_FlashProgram(CFO_Adrss,16,cfo_data_encrypt);

    		mTlvBuf[0] = CFO_CALIB;
    		mTlvBuf[1] = 0x03;
    		mTlvBuf[2] = 0x01;
    		mTlvBuf[3] = ( crc >> 8) & 0xFF;
    		mTlvBuf[4] = crc & 0xFF;
    		UWB_Hif_SendRsp(mTlvBuf, 5);
    	}
    	else if(tlv->size <= (sizeof(cfo_data) - 4))
    	{
    	for(uint32_t i = 0;i<IFR_SIZE;i++)
    	{
    		s_buff[i] = *(volatile uint32_t *)(startAdrss + i * 4);
    	}
    	uint8_t cfodata_sbf[16] = {0};
    	uint8_t cfodata_sbfdecrypt[16] = {0};//用于存放flash中解密后的cfo_data
    	memset(cfodata_sbf, 0xFF, 16);
    	memset(cfodata_sbfdecrypt, 0xFF, 16);
    	memcpy(cfodata_sbf, &s_buff[16], 16);
    	AES_128_ECB_Decrypt(cfodata_sbf,16,AES_Key,cfodata_sbfdecrypt);
    	PRINTF("cfodata_sbfdecrypt: ");
    	for (int i=0; i<16; i++) {
    	    PRINTF("%02X \n", cfodata_sbfdecrypt[i]);
    	}
    	PRINTF("\r\n");
    	uint8_t cfo_data1[16] = {0}; //用于存放发送的cfo_data
    	memset(cfo_data1, 0xFF, 16);
    	uint8_t cfodata_tlv[16] = {0}; //用于存放加密后的cfo_data1

    	uint16_t crc_cpt = NV_ComputeCrc(cfodata_sbfdecrypt,12);
    	PRINTF("crc_cpt = %04X\r\n",crc_cpt);

    	//PRINTF("cfodata_sbfdecrypt[12] = %02X\r\n",cfodata_sbfdecrypt[12]);
    	//PRINTF("cfodata_sbfdecrypt[13] = %02X\r\n",cfodata_sbfdecrypt[13]);
    	uint16_t combined = ( (uint16_t)cfodata_sbfdecrypt[12] << 8 ) | (uint16_t)cfodata_sbfdecrypt[13];
    	PRINTF("combined = %04X\r\n",combined);
    	//if(crc_cpt == combined)
    	//{
    		//构造需要写入的加密数据包
        	// 设置包头（大端序）
        	cfo_data1[0] = (PACKET_HEADER >> 8) & 0xFF;  // 0xEF
        	cfo_data1[1] = PACKET_HEADER & 0xFF;         // 0x01
        	PRINTF("tlv->value: ");
        	for (int i=0; i<tlv->size; i++) {
        	    PRINTF("%02X \n", tlv->value[i]);
        	}
        	PRINTF("\r\n");
        	memcpy(&cfo_data1[2], tlv->value, tlv->size);
        	uint16_t crc1 = NV_ComputeCrc(cfo_data1, 12); // 假设CRC为0x1234
        	uint16_t reversed_crc = ((crc1 & 0xFF) << 8) | ((crc1 >> 8) & 0xFF); // 反转字节：0x1234 → 0x3412
        	PRINTF("reversed_crc = 0x%04X\r\n", reversed_crc);
        	memcpy(&cfo_data1[12], &reversed_crc, 2);
        	PRINTF("cfo_data1: ");
        	for (int i=0; i<16; i++) {
        	    PRINTF("%02X \n", cfo_data1[i]);
        	}
        	PRINTF("\r\n");
        	memset(&s_buff[16], 0xFF, 16);
        	AES_128_ECB_Encrypt(cfo_data1,16,AES_Key,cfodata_tlv);
        	PRINTF("cfodata_tlv: ");
        	for (int i=0; i<16; i++) {
        	    PRINTF("%02X \n", cfodata_tlv[i]);
        	}
        	PRINTF("\r\n");
        	memcpy(&s_buff[16], &cfodata_tlv, 16);

    		status = HAL_FlashEraseSector(startAdrss, PLATFORM_INTFLASH_SECTOR_SIZE);
    		if (kStatus_HAL_Flash_Success == status)
    		{
    			HAL_FlashProgram(startAdrss,PLATFORM_INTFLASH_SECTOR_SIZE,(uint8_t*)s_buff);
    			PRINTF("HAL_FlashProgram\r\n");
    			mTlvBuf[0] = CFO_CALIB;
    			mTlvBuf[1] = 0x03;
    			mTlvBuf[2] = 0x02;
        		mTlvBuf[3] = ( crc1 >> 8) & 0xFF;
        		mTlvBuf[4] = crc1 & 0xFF;
        		UWB_Hif_SendRsp(mTlvBuf, 5);
    		}
    	//}
    	else
    	{
			mTlvBuf[0] = 0x05;
			mTlvBuf[1] = 0x01;
			mTlvBuf[2] = 0x01;
    		mTlvBuf[3] = 0xFF;
    		mTlvBuf[4] = 0xFF;
    		UWB_Hif_SendRsp(mTlvBuf, 5);
    	}
    	}
    }break;
    case POW_CALIB:{
    	hal_flash_status_t status = 0;
    	memset(s_buff, 0xFF, PLATFORM_INTFLASH_SECTOR_SIZE);
    	status = HAL_FlashVerifyErase(POW_Adrss, 0x40u, kHAL_Flash_MarginValueNormal);
    	uint8_t pow_data[16] = {0};
    	memset(pow_data, 0xFF, 16);
    	// 设置包头（大端序）
    	pow_data[0] = (PACKET_HEADER >> 8) & 0xFF;  // 0xEF
    	pow_data[1] = PACKET_HEADER & 0xFF;         // 0x01

    	if(status == kStatus_HAL_Flash_Success && tlv->size <= (sizeof(pow_data) - 4))
    	{
    		memcpy(&pow_data[2], tlv->value, tlv->size);
    		uint16_t  crc = NV_ComputeCrc(pow_data,12);
    		uint8_t  pow_data_encrypt[16] = {0};
    		PRINTF("NV_ComputeCrc = %04X\r\n",crc);
    		pow_data[12] = ( crc >> 8) & 0xFF;
    		pow_data[13] = crc & 0xFF;
    		AES_128_ECB_Encrypt(pow_data,16,AES_Key,pow_data_encrypt);
    		HAL_FlashProgram(POW_Adrss,16,pow_data_encrypt);

    		mTlvBuf[0] = POW_CALIB;
    		mTlvBuf[1] = 0x03;
    		mTlvBuf[2] = 0x01;
    		mTlvBuf[3] = ( crc >> 8) & 0xFF;
    		mTlvBuf[4] = crc & 0xFF;
    		UWB_Hif_SendRsp(mTlvBuf, 5);
    	}
    	else if(tlv->size <= (sizeof(pow_data) - 4))
    	{
    	for(uint32_t i = 0;i<IFR_SIZE;i++)
    	{
    		s_buff[i] = *(volatile uint32_t *)(startAdrss + i * 4);
    	}
    	uint8_t powdata_sbf[16] = {0};
    	uint8_t powdata_sbfdecrypt[16] = {0};//用于存放flash中解密后的cfo_data
    	memset(powdata_sbf, 0xFF, 16);
    	memset(powdata_sbfdecrypt, 0xFF, 16);
    	memcpy(powdata_sbf, &s_buff[32], 16);
    	AES_128_ECB_Decrypt(powdata_sbf,16,AES_Key,powdata_sbfdecrypt);
    	PRINTF("powdata_sbfdecrypt: ");
    	for (int i=0; i<16; i++) {
    	    PRINTF("%02X \n", powdata_sbfdecrypt[i]);
    	}
    	PRINTF("\r\n");
    	uint8_t pow_data1[16] = {0}; //用于存放发送的cfo_data
    	memset(pow_data1, 0xFF, 16);
    	uint8_t powdata_tlv[16] = {0}; //用于存放加密后的cfo_data1

    	uint16_t crc_cpt = NV_ComputeCrc(powdata_sbfdecrypt,12);
    	PRINTF("crc_cpt = %04X\r\n",crc_cpt);

    	//PRINTF("powdata_sbfdecrypt[12] = %02X\r\n",powdata_sbfdecrypt[12]);
    	//PRINTF("powdata_sbfdecrypt[13] = %02X\r\n",powdata_sbfdecrypt[13]);
    	uint16_t combined = ( (uint16_t)powdata_sbfdecrypt[12] << 8 ) | (uint16_t)powdata_sbfdecrypt[13];
    	PRINTF("combined = %04X\r\n",combined);
    	//if(crc_cpt == combined)
    	//{
    		//构造需要写入的加密数据包
        	// 设置包头（大端序）
    		pow_data1[0] = (PACKET_HEADER >> 8) & 0xFF;  // 0xEF
        	pow_data1[1] = PACKET_HEADER & 0xFF;         // 0x01
        	PRINTF("tlv->value: ");
        	for (int i=0; i<tlv->size; i++) {
        	    PRINTF("%02X \n", tlv->value[i]);
        	}
        	PRINTF("\r\n");
        	memcpy(&pow_data1[2], tlv->value, tlv->size);
        	uint16_t crc1 = NV_ComputeCrc(pow_data1, 12); // 假设CRC为0x1234
        	uint16_t reversed_crc = ((crc1 & 0xFF) << 8) | ((crc1 >> 8) & 0xFF); // 反转字节：0x1234 → 0x3412
        	PRINTF("reversed_crc = 0x%04X\r\n", reversed_crc);
        	memcpy(&pow_data1[12], &reversed_crc, 2);
        	PRINTF("pow_data1: ");
        	for (int i=0; i<16; i++) {
        	    PRINTF("%02X \n", pow_data1[i]);
        	}
        	PRINTF("\r\n");
        	memset(&s_buff[32], 0xFF, 16);
        	AES_128_ECB_Encrypt(pow_data1,16,AES_Key,powdata_tlv);
        	PRINTF("powdata_tlv: ");
        	for (int i=0; i<16; i++) {
        	    PRINTF("%02X \n", powdata_tlv[i]);
        	}
        	PRINTF("\r\n");
        	memcpy(&s_buff[32], &powdata_tlv, 16);

    		status = HAL_FlashEraseSector(startAdrss, PLATFORM_INTFLASH_SECTOR_SIZE);
    		if (kStatus_HAL_Flash_Success == status)
    		{
    			HAL_FlashProgram(startAdrss,PLATFORM_INTFLASH_SECTOR_SIZE,(uint8_t*)s_buff);
    			PRINTF("HAL_FlashProgram\r\n");
    			mTlvBuf[0] = POW_CALIB;
    			mTlvBuf[1] = 0x03;
    			mTlvBuf[2] = 0x02;
        		mTlvBuf[3] = ( crc1 >> 8) & 0xFF;
        		mTlvBuf[4] = crc1 & 0xFF;
        		UWB_Hif_SendRsp(mTlvBuf, 5);
    		}
    	//}
    	else
    	{
			mTlvBuf[0] = 0x05;
			mTlvBuf[1] = 0x01;
			mTlvBuf[2] = 0x01;
    		mTlvBuf[3] = 0xFF;
    		mTlvBuf[4] = 0xFF;
    		UWB_Hif_SendRsp(mTlvBuf, 5);
    	}
    	}
    }break;
    case IDEN_CMD:{
    	hal_flash_status_t status = 0;
    	memset(s_buff, 0xFF, PLATFORM_INTFLASH_SECTOR_SIZE);
    	status = HAL_FlashVerifyErase(IDEN_Adrss, 0x40u, kHAL_Flash_MarginValueNormal);
    	uint8_t iden_data[16] = {0};
    	memset(iden_data, 0xFF, 16);
    	// 设置包头（大端序）
    	iden_data[0] = (PACKET_HEADER >> 8) & 0xFF;  // 0xEF
    	iden_data[1] = PACKET_HEADER & 0xFF;         // 0x01

    	if(status == kStatus_HAL_Flash_Success && tlv->size <= (sizeof(iden_data) - 4))
    	{
    		memcpy(&iden_data[2], tlv->value, tlv->size);
    		uint16_t  crc = NV_ComputeCrc(iden_data,12);
    		uint8_t  iden_data_encrypt[16] = {0};
    		PRINTF("NV_ComputeCrc = %04X\r\n",crc);
    		iden_data[12] = ( crc >> 8) & 0xFF;
    		iden_data[13] = crc & 0xFF;
    		AES_128_ECB_Encrypt(iden_data,16,AES_Key,iden_data_encrypt);
    		HAL_FlashProgram(IDEN_Adrss,16,iden_data_encrypt);

    		mTlvBuf[0] = IDEN_CMD;
    		mTlvBuf[1] = 0x03;
    		mTlvBuf[2] = 0x01;
    		mTlvBuf[3] = ( crc >> 8) & 0xFF;
    		mTlvBuf[4] = crc & 0xFF;
    		UWB_Hif_SendRsp(mTlvBuf, 5);
    	}
    	else if(tlv->size <= (sizeof(iden_data) - 4))
    	{
    	for(uint32_t i = 0;i<IFR_SIZE;i++)
    	{
    		s_buff[i] = *(volatile uint32_t *)(startAdrss + i * 4);
    	}
    	uint8_t idendata_sbf[16] = {0};
    	uint8_t idendata_sbfdecrypt[16] = {0};//用于存放flash中解密后的cfo_data
    	memset(idendata_sbf, 0xFF, 16);
    	memset(idendata_sbfdecrypt, 0xFF, 16);
    	memcpy(idendata_sbf, &s_buff[48], 16);
    	AES_128_ECB_Decrypt(idendata_sbf,16,AES_Key,idendata_sbfdecrypt);
    	PRINTF("idendata_sbfdecrypt: ");
    	for (int i=0; i<16; i++) {
    	    PRINTF("%02X \n", idendata_sbfdecrypt[i]);
    	}
    	PRINTF("\r\n");
    	uint8_t iden_data1[16] = {0}; //用于存放发送的cfo_data
    	memset(iden_data1, 0xFF, 16);
    	uint8_t idendata_tlv[16] = {0}; //用于存放加密后的cfo_data1

    	uint16_t crc_cpt = NV_ComputeCrc(idendata_sbfdecrypt,12);
    	PRINTF("crc_cpt = %04X\r\n",crc_cpt);

    	//PRINTF("idendata_sbfdecrypt[12] = %02X\r\n",idendata_sbfdecrypt[12]);
    	//PRINTF("idendata_sbfdecrypt[13] = %02X\r\n",idendata_sbfdecrypt[13]);
    	uint16_t combined = ( (uint16_t)idendata_sbfdecrypt[12] << 8 ) | (uint16_t)idendata_sbfdecrypt[13];
    	PRINTF("combined = %04X\r\n",combined);
    	//if(crc_cpt == combined)
    	//{
    		//构造需要写入的加密数据包
        	// 设置包头（大端序）
    		iden_data1[0] = (PACKET_HEADER >> 8) & 0xFF;  // 0xEF
    		iden_data1[1] = PACKET_HEADER & 0xFF;         // 0x01
        	PRINTF("tlv->value: ");
        	for (int i=0; i<tlv->size; i++) {
        	    PRINTF("%02X \n", tlv->value[i]);
        	}
        	PRINTF("\r\n");
        	memcpy(&iden_data1[2], tlv->value, tlv->size);
        	uint16_t crc1 = NV_ComputeCrc(iden_data1, 12); // 假设CRC为0x1234
        	uint16_t reversed_crc = ((crc1 & 0xFF) << 8) | ((crc1 >> 8) & 0xFF); // 反转字节：0x1234 → 0x3412
        	PRINTF("reversed_crc = 0x%04X\r\n", reversed_crc);
        	memcpy(&iden_data1[12], &reversed_crc, 2);
        	PRINTF("iden_data1: ");
        	for (int i=0; i<16; i++) {
        	    PRINTF("%02X \n", iden_data1[i]);
        	}
        	PRINTF("\r\n");
        	memset(&s_buff[48], 0xFF, 16);
        	AES_128_ECB_Encrypt(iden_data1,16,AES_Key,idendata_tlv);
        	PRINTF("idendata_tlv: ");
        	for (int i=0; i<16; i++) {
        	    PRINTF("%02X \n", idendata_tlv[i]);
        	}
        	PRINTF("\r\n");
        	memcpy(&s_buff[48], &idendata_tlv, 16);

    		status = HAL_FlashEraseSector(startAdrss, PLATFORM_INTFLASH_SECTOR_SIZE);
    		if (kStatus_HAL_Flash_Success == status)
    		{
    			HAL_FlashProgram(startAdrss,PLATFORM_INTFLASH_SECTOR_SIZE,(uint8_t*)s_buff);
    			PRINTF("HAL_FlashProgram\r\n");
    			mTlvBuf[0] = IDEN_CMD;
    			mTlvBuf[1] = 0x03;
    			mTlvBuf[2] = 0x02;
        		mTlvBuf[3] = ( crc1 >> 8) & 0xFF;
        		mTlvBuf[4] = crc1 & 0xFF;
        		UWB_Hif_SendRsp(mTlvBuf, 5);
    		}
    	//}
    	else
    	{
			mTlvBuf[0] = 0x05;
			mTlvBuf[1] = 0x01;
			mTlvBuf[2] = 0x01;
    		mTlvBuf[3] = 0xFF;
    		mTlvBuf[4] = 0xFF;
    		UWB_Hif_SendRsp(mTlvBuf, 5);
    	}
    	}
    }break;
    case QRCODE_CMD:{
    	hal_flash_status_t status = 0;
    	memset(s_buff, 0xFF, PLATFORM_INTFLASH_SECTOR_SIZE);
    	status = HAL_FlashVerifyErase(QRCODE_Adrss, 0x100u, kHAL_Flash_MarginValueNormal);
    	uint8_t qrcode_data[64] = {0};
    	memset(qrcode_data, 0xFF, 64);
    	// 设置包头（大端序）
    	qrcode_data[0] = (PACKET_HEADER >> 8) & 0xFF;  // 0xEF
    	qrcode_data[1] = PACKET_HEADER & 0xFF;         // 0x01

    	if(status == kStatus_HAL_Flash_Success && tlv->size <= (sizeof(qrcode_data) - 4))
    	{
    		memcpy(&qrcode_data[2], tlv->value, tlv->size);
    		uint16_t  crc = NV_ComputeCrc(qrcode_data,60);
    		uint8_t  qrcode_data_encrypt[64] = {0};
    		PRINTF("NV_ComputeCrc = %04X\r\n",crc);
    		qrcode_data[60] = ( crc >> 8) & 0xFF;
    		qrcode_data[61] = crc & 0xFF;
    		AES_128_ECB_Encrypt(qrcode_data,64,AES_Key,qrcode_data_encrypt);
    		HAL_FlashProgram(QRCODE_Adrss,64,qrcode_data_encrypt);

    		mTlvBuf[0] = QRCODE_CMD;
    		mTlvBuf[1] = 0x03;
    		mTlvBuf[2] = 0x01;
    		mTlvBuf[3] = ( crc >> 8) & 0xFF;
    		mTlvBuf[4] = crc & 0xFF;
    		UWB_Hif_SendRsp(mTlvBuf, 5);
    	}
    	else if(tlv->size <= (sizeof(qrcode_data) - 4))
    	{
    	for(uint32_t i = 0;i<IFR_SIZE;i++)
    	{
    		s_buff[i] = *(volatile uint32_t *)(startAdrss + i * 4);
    	}
    	uint8_t qrcodedata_sbf[64] = {0};
    	uint8_t qrcodedata_sbfdecrypt[64] = {0};//用于存放flash中解密后的qrcode_data
    	memset(qrcodedata_sbf, 0xFF, 64);
    	memset(qrcodedata_sbfdecrypt, 0xFF, 64);
    	memcpy(qrcodedata_sbf, &s_buff[64], 64);
    	AES_128_ECB_Decrypt(qrcodedata_sbf,64,AES_Key,qrcodedata_sbfdecrypt);
    	PRINTF("qrcodedata_sbfdecrypt: ");
    	for (int i=0; i<64; i++) {
    	    PRINTF("%02X \n", qrcodedata_sbfdecrypt[i]);
    	}
    	PRINTF("\r\n");
    	uint8_t qrcode_data1[64] = {0}; //用于存放发送的qrcode_data
    	memset(qrcode_data1, 0xFF, 64);
    	uint8_t qrcodedata_tlv[64] = {0}; //用于存放加密后的qrcode_data1

    	uint16_t crc_cpt = NV_ComputeCrc(qrcodedata_sbfdecrypt,60);
    	PRINTF("crc_cpt = %04X\r\n",crc_cpt);

    	//PRINTF("qrcodedata_sbfdecrypt[60] = %02X\r\n",qrcodedata_sbfdecrypt[60]);
    	//PRINTF("qrcodedata_sbfdecrypt[61] = %02X\r\n",qrcodedata_sbfdecrypt[61]);
    	uint16_t combined = ( (uint16_t)qrcodedata_sbfdecrypt[60] << 8 ) | (uint16_t)qrcodedata_sbfdecrypt[61];
    	PRINTF("combined = %04X\r\n",combined);
    	//if(crc_cpt == combined)
    	//{
    		//构造需要写入的加密数据包
        	// 设置包头（大端序）
    		qrcode_data1[0] = (PACKET_HEADER >> 8) & 0xFF;  // 0xEF
    		qrcode_data1[1] = PACKET_HEADER & 0xFF;         // 0x01
        	PRINTF("tlv->value: ");
        	for (int i=0; i<tlv->size; i++) {
        	    PRINTF("%02X \n", tlv->value[i]);
        	}
        	PRINTF("\r\n");
        	memcpy(&qrcode_data1[2], tlv->value, tlv->size);
        	uint16_t crc1 = NV_ComputeCrc(qrcode_data1, 60); // 假设CRC为0x1234
        	uint16_t reversed_crc = ((crc1 & 0xFF) << 8) | ((crc1 >> 8) & 0xFF); // 反转字节：0x1234 → 0x3412
        	PRINTF("reversed_crc = 0x%04X\r\n", reversed_crc);
        	memcpy(&qrcode_data1[60], &reversed_crc, 2);
        	PRINTF("qrcode_data1: ");
        	for (int i=0; i<64; i++) {
        	    PRINTF("%02X \n", qrcode_data1[i]);
        	}
        	PRINTF("\r\n");
        	memset(&s_buff[64], 0xFF, 64);
        	AES_128_ECB_Encrypt(qrcode_data1,64,AES_Key,qrcodedata_tlv);
        	PRINTF("qrcodedata_tlv: ");
        	for (int i=0; i<64; i++) {
        	    PRINTF("%02X \n", qrcodedata_tlv[i]);
        	}
        	PRINTF("\r\n");
        	memcpy(&s_buff[64], &qrcodedata_tlv, 64);

    		status = HAL_FlashEraseSector(startAdrss, PLATFORM_INTFLASH_SECTOR_SIZE);
    		if (kStatus_HAL_Flash_Success == status)
    		{
    			HAL_FlashProgram(startAdrss,PLATFORM_INTFLASH_SECTOR_SIZE,(uint8_t*)s_buff);
    			PRINTF("HAL_FlashProgram\r\n");
    			mTlvBuf[0] = QRCODE_CMD;
    			mTlvBuf[1] = 0x03;
    			mTlvBuf[2] = 0x02;
        		mTlvBuf[3] = ( crc1 >> 8) & 0xFF;
        		mTlvBuf[4] = crc1 & 0xFF;
        		UWB_Hif_SendRsp(mTlvBuf, 5);
    		}
    	//}
    	else
    	{
			mTlvBuf[0] = 0x05;
			mTlvBuf[1] = 0x01;
			mTlvBuf[2] = 0x01;
    		mTlvBuf[3] = 0xFF;
    		mTlvBuf[4] = 0xFF;
    		UWB_Hif_SendRsp(mTlvBuf, 5);
    	}
    	}
    }break;
    case TWR_CALIB:{
    	hal_flash_status_t status = 0;
    	memset(s_buff, 0xFF, PLATFORM_INTFLASH_SECTOR_SIZE);
    	status = HAL_FlashVerifyErase(TWR_Adrss, 0x100u, kHAL_Flash_MarginValueNormal);
    	uint8_t twr_data[64] = {0};
    	memset(twr_data, 0xFF, 64);
    	// 设置包头（大端序）
    	twr_data[0] = (PACKET_HEADER >> 8) & 0xFF;  // 0xEF
    	twr_data[1] = PACKET_HEADER & 0xFF;         // 0x01

    	if(status == kStatus_HAL_Flash_Success && tlv->size <= (sizeof(twr_data) - 4))
    	{
    		memcpy(&twr_data[2], tlv->value, tlv->size);
    		uint16_t  crc = NV_ComputeCrc(twr_data,60);
    		uint8_t  twr_data_encrypt[64] = {0};
    		PRINTF("NV_ComputeCrc = %04X\r\n",crc);
    		twr_data[60] = ( crc >> 8) & 0xFF;
    		twr_data[61] = crc & 0xFF;
    		AES_128_ECB_Encrypt(twr_data,64,AES_Key,twr_data_encrypt);
    		HAL_FlashProgram(TWR_Adrss,64,twr_data_encrypt);

    		mTlvBuf[0] = TWR_CALIB;
    		mTlvBuf[1] = 0x03;
    		mTlvBuf[2] = 0x01;
    		mTlvBuf[3] = ( crc >> 8) & 0xFF;
    		mTlvBuf[4] = crc & 0xFF;
    		UWB_Hif_SendRsp(mTlvBuf, 5);
    	}
    	else if(tlv->size <= (sizeof(twr_data) - 4))
    	{
    	for(uint32_t i = 0;i<IFR_SIZE;i++)
    	{
    		s_buff[i] = *(volatile uint32_t *)(startAdrss + i * 4);
    	}
    	uint8_t twrdata_sbf[64] = {0};
    	uint8_t twrdata_sbfdecrypt[64] = {0};//用于存放flash中解密后的twr_data
    	memset(twrdata_sbf, 0xFF, 64);
    	memset(twrdata_sbfdecrypt, 0xFF, 64);
    	memcpy(twrdata_sbf, &s_buff[128], 64);
    	AES_128_ECB_Decrypt(twrdata_sbf,64,AES_Key,twrdata_sbfdecrypt);
    	PRINTF("twrdata_sbfdecrypt: ");
    	for (int i=0; i<64; i++) {
    	    PRINTF("%02X \n", twrdata_sbfdecrypt[i]);
    	}
    	PRINTF("\r\n");
    	uint8_t twr_data1[64] = {0}; //用于存放发送的twr_data
    	memset(twr_data1, 0xFF, 64);
    	uint8_t twrdata_tlv[64] = {0}; //用于存放加密后的twr_data1

    	uint16_t crc_cpt = NV_ComputeCrc(twrdata_sbfdecrypt,60);
    	PRINTF("crc_cpt = %04X\r\n",crc_cpt);

    	//PRINTF("twrdata_sbfdecrypt[60] = %02X\r\n",twrdata_sbfdecrypt[60]);
    	//PRINTF("twrdata_sbfdecrypt[61] = %02X\r\n",twrdata_sbfdecrypt[61]);
    	uint16_t combined = ( (uint16_t)twrdata_sbfdecrypt[60] << 8 ) | (uint16_t)twrdata_sbfdecrypt[61];
    	PRINTF("combined = %04X\r\n",combined);
    	//if(crc_cpt == combined)
    	//{
    		//构造需要写入的加密数据包
        	// 设置包头（大端序）
    		twr_data1[0] = (PACKET_HEADER >> 8) & 0xFF;  // 0xEF
    		twr_data1[1] = PACKET_HEADER & 0xFF;         // 0x01
        	PRINTF("tlv->value: ");
        	for (int i=0; i<tlv->size; i++) {
        	    PRINTF("%02X \n", tlv->value[i]);
        	}
        	PRINTF("\r\n");
        	memcpy(&twr_data1[2], tlv->value, tlv->size);
        	uint16_t crc1 = NV_ComputeCrc(twr_data1, 60); // 假设CRC为0x1234
        	uint16_t reversed_crc = ((crc1 & 0xFF) << 8) | ((crc1 >> 8) & 0xFF); // 反转字节：0x1234 → 0x3412
        	PRINTF("reversed_crc = 0x%04X\r\n", reversed_crc);
        	memcpy(&twr_data1[60], &reversed_crc, 2);
        	PRINTF("twr_data1: ");
        	for (int i=0; i<64; i++) {
        	    PRINTF("%02X \n", twr_data1[i]);
        	}
        	PRINTF("\r\n");
        	memset(&s_buff[128], 0xFF, 64);
        	AES_128_ECB_Encrypt(twr_data1,64,AES_Key,twrdata_tlv);
        	PRINTF("twrdata_tlv: ");
        	for (int i=0; i<64; i++) {
        	    PRINTF("%02X \n", twrdata_tlv[i]);
        	}
        	PRINTF("\r\n");
        	memcpy(&s_buff[128], &twrdata_tlv, 64);

    		status = HAL_FlashEraseSector(startAdrss, PLATFORM_INTFLASH_SECTOR_SIZE);
    		if (kStatus_HAL_Flash_Success == status)
    		{
    			HAL_FlashProgram(startAdrss,PLATFORM_INTFLASH_SECTOR_SIZE,(uint8_t*)s_buff);
    			PRINTF("HAL_FlashProgram\r\n");
    			mTlvBuf[0] = TWR_CALIB;
    			mTlvBuf[1] = 0x03;
    			mTlvBuf[2] = 0x02;
        		mTlvBuf[3] = ( crc1 >> 8) & 0xFF;
        		mTlvBuf[4] = crc1 & 0xFF;
        		UWB_Hif_SendRsp(mTlvBuf, 5);
    		}
    	//}
    	else
    	{
			mTlvBuf[0] = 0x05;
			mTlvBuf[1] = 0x01;
			mTlvBuf[2] = 0x01;
    		mTlvBuf[3] = 0xFF;
    		mTlvBuf[4] = 0xFF;
    		UWB_Hif_SendRsp(mTlvBuf, 5);
    	}
    	}
    }break;
    case PDOA_CALIB:{
    	hal_flash_status_t status = 0;
    	memset(s_buff, 0xFF, PLATFORM_INTFLASH_SECTOR_SIZE);
    	status = HAL_FlashVerifyErase(PDOA_Adrss, 0x100u, kHAL_Flash_MarginValueNormal);
    	uint8_t pdoa_data[64] = {0};
    	memset(pdoa_data, 0xFF, 64);
    	// 设置包头（大端序）
    	pdoa_data[0] = (PACKET_HEADER >> 8) & 0xFF;  // 0xEF
    	pdoa_data[1] = PACKET_HEADER & 0xFF;         // 0x01

    	if(status == kStatus_HAL_Flash_Success && tlv->size <= (sizeof(pdoa_data) - 4))
    	{
    		memcpy(&pdoa_data[2], tlv->value, tlv->size);
    		uint16_t  crc = NV_ComputeCrc(pdoa_data,60);
    		uint8_t  pdoa_data_encrypt[64] = {0};
    		PRINTF("NV_ComputeCrc = %04X\r\n",crc);
    		pdoa_data[60] = ( crc >> 8) & 0xFF;
    		pdoa_data[61] = crc & 0xFF;
    		AES_128_ECB_Encrypt(pdoa_data,64,AES_Key,pdoa_data_encrypt);
    		HAL_FlashProgram(PDOA_Adrss,64,pdoa_data_encrypt);

    		mTlvBuf[0] = PDOA_CALIB;
    		mTlvBuf[1] = 0x03;
    		mTlvBuf[2] = 0x01;
    		mTlvBuf[3] = ( crc >> 8) & 0xFF;
    		mTlvBuf[4] = crc & 0xFF;
    		UWB_Hif_SendRsp(mTlvBuf, 5);
    	}
    	else if(tlv->size <= (sizeof(pdoa_data) - 4))
    	{
    	for(uint32_t i = 0;i<IFR_SIZE;i++)
    	{
    		s_buff[i] = *(volatile uint32_t *)(startAdrss + i * 4);
    	}
    	uint8_t pdoadata_sbf[64] = {0};
    	uint8_t pdoadata_sbfdecrypt[64] = {0};//用于存放flash中解密后的qrcode_data
    	memset(pdoadata_sbf, 0xFF, 64);
    	memset(pdoadata_sbfdecrypt, 0xFF, 64);
    	memcpy(pdoadata_sbf, &s_buff[192], 64);
    	AES_128_ECB_Decrypt(pdoadata_sbf,64,AES_Key,pdoadata_sbfdecrypt);
    	PRINTF("pdoadata_sbfdecrypt: ");
    	for (int i=0; i<64; i++) {
    	    PRINTF("%02X \n", pdoadata_sbfdecrypt[i]);
    	}
    	PRINTF("\r\n");
    	uint8_t pdoa_data1[64] = {0}; //用于存放发送的qrcode_data
    	memset(pdoa_data1, 0xFF, 64);
    	uint8_t pdoadata_tlv[64] = {0}; //用于存放加密后的qrcode_data1

    	uint16_t crc_cpt = NV_ComputeCrc(pdoadata_sbfdecrypt,60);
    	PRINTF("crc_cpt = %04X\r\n",crc_cpt);

    	//PRINTF("pdoadata_sbfdecrypt[60] = %02X\r\n",pdoadata_sbfdecrypt[60]);
    	//PRINTF("pdoadata_sbfdecrypt[61] = %02X\r\n",pdoadata_sbfdecrypt[61]);
    	uint16_t combined = ( (uint16_t)pdoadata_sbfdecrypt[60] << 8 ) | (uint16_t)pdoadata_sbfdecrypt[61];
    	PRINTF("combined = %04X\r\n",combined);
    	//if(crc_cpt == combined)
    	//{
    		//构造需要写入的加密数据包
        	// 设置包头（大端序）
    		pdoa_data1[0] = (PACKET_HEADER >> 8) & 0xFF;  // 0xEF
    		pdoa_data1[1] = PACKET_HEADER & 0xFF;         // 0x01
        	PRINTF("tlv->value: ");
        	for (int i=0; i<tlv->size; i++) {
        	    PRINTF("%02X \n", tlv->value[i]);
        	}
        	PRINTF("\r\n");
        	memcpy(&pdoa_data1[2], tlv->value, tlv->size);
        	uint16_t crc1 = NV_ComputeCrc(pdoa_data1, 60); // 假设CRC为0x1234
        	uint16_t reversed_crc = ((crc1 & 0xFF) << 8) | ((crc1 >> 8) & 0xFF); // 反转字节：0x1234 → 0x3412
        	PRINTF("reversed_crc = 0x%04X\r\n", reversed_crc);
        	memcpy(&pdoa_data1[60], &reversed_crc, 2);
        	PRINTF("pdoa_data1: ");
        	for (int i=0; i<64; i++) {
        	    PRINTF("%02X \n", pdoa_data1[i]);
        	}
        	PRINTF("\r\n");
        	memset(&s_buff[192], 0xFF, 64);
        	AES_128_ECB_Encrypt(pdoa_data1,64,AES_Key,pdoadata_tlv);
        	PRINTF("pdoadata_tlv: ");
        	for (int i=0; i<64; i++) {
        	    PRINTF("%02X \n", pdoadata_tlv[i]);
        	}
        	PRINTF("\r\n");
        	memcpy(&s_buff[192], &pdoadata_tlv, 64);

    		status = HAL_FlashEraseSector(startAdrss, PLATFORM_INTFLASH_SECTOR_SIZE);
    		if (kStatus_HAL_Flash_Success == status)
    		{
    			HAL_FlashProgram(startAdrss,PLATFORM_INTFLASH_SECTOR_SIZE,(uint8_t*)s_buff);
    			PRINTF("HAL_FlashProgram\r\n");
    			mTlvBuf[0] = PDOA_CALIB;
    			mTlvBuf[1] = 0x03;
    			mTlvBuf[2] = 0x02;
        		mTlvBuf[3] = ( crc1 >> 8) & 0xFF;
        		mTlvBuf[4] = crc1 & 0xFF;
        		UWB_Hif_SendRsp(mTlvBuf, 5);
    		}
    	//}
    	else
    	{
			mTlvBuf[0] = 0x05;
			mTlvBuf[1] = 0x01;
			mTlvBuf[2] = 0x01;
    		mTlvBuf[3] = 0xFF;
    		mTlvBuf[4] = 0xFF;
    		UWB_Hif_SendRsp(mTlvBuf, 5);
    	}
    	}
    }break;
    case ROOT_CACERT:{
    	hal_flash_status_t status = 0;
    	memset(s_buff, 0xFF, PLATFORM_INTFLASH_SECTOR_SIZE);
    	status = HAL_FlashVerifyErase(ROOT_CA_CERT_Adrss, 0x360u, kHAL_Flash_MarginValueNormal);
    	memset(rootcert_data, 0xFF, 864);
    	// 设置包头（大端序）
    	rootcert_data[0] = (PACKET_HEADER >> 8) & 0xFF;  // 0xEF
    	rootcert_data[1] = PACKET_HEADER & 0xFF;         // 0x01

    	if(status == kStatus_HAL_Flash_Success && tlv->size <= (sizeof(rootcert_data) - 4))
    	{
    		memcpy(&rootcert_data[2], tlv->value, tlv->size);
    		uint16_t  crc = NV_ComputeCrc(rootcert_data,860);
    		PRINTF("NV_ComputeCrc = %04X\r\n",crc);
    		rootcert_data[860] = ( crc >> 8) & 0xFF;
    		rootcert_data[861] = crc & 0xFF;
    		AES_128_ECB_Encrypt(rootcert_data,864,AES_Key,rootcert_data_encrypt);
    		HAL_FlashProgram(ROOT_CA_CERT_Adrss,864,rootcert_data_encrypt);

    		mTlvBuf[0] = ROOT_CACERT;
    		mTlvBuf[1] = 0x03;
    		mTlvBuf[2] = 0x01;
    		mTlvBuf[3] = ( crc >> 8) & 0xFF;
    		mTlvBuf[4] = crc & 0xFF;
    		UWB_Hif_SendRsp(mTlvBuf, 5);
    	}
    	else if(tlv->size <= (sizeof(rootcert_data) - 4))
    	{
    	for(uint32_t i = 0;i<IFR_SIZE;i++)
    	{
    		s_buff[i] = *(volatile uint32_t *)(startAdrss + i * 4);
    	}
    	memset(rootcertdata_sbf, 0xFF, 864);
    	memset(rootcertdata_sbfdecrypt, 0xFF, 864);
    	memcpy(rootcertdata_sbf, &s_buff[256], 864);
    	AES_128_ECB_Decrypt(rootcertdata_sbf,864,AES_Key,rootcertdata_sbfdecrypt);
    	//PRINTF("rootcertdata_sbfdecrypt: ");
    	//for (int i=0; i<864; i++) {
    	//    PRINTF("%02X \n", rootcertdata_sbfdecrypt[i]);
    	//}
    	//PRINTF("\r\n");
    	memset(rootcert_data1, 0xFF, 864);

    	uint16_t crc_cpt = NV_ComputeCrc(rootcertdata_sbfdecrypt,860);
    	PRINTF("crc_cpt = %04X\r\n",crc_cpt);

    	//PRINTF("rootcertdata_sbfdecrypt[860] = %02X\r\n",rootcertdata_sbfdecrypt[860]);
    	//PRINTF("rootcertdata_sbfdecrypt[861] = %02X\r\n",rootcertdata_sbfdecrypt[861]);
    	uint16_t combined = ( (uint16_t)rootcertdata_sbfdecrypt[860] << 8 ) | (uint16_t)rootcertdata_sbfdecrypt[861];
    	PRINTF("combined = %04X\r\n",combined);
    	//if(crc_cpt == combined)
    	//{
    		//构造需要写入的加密数据包
        	// 设置包头（大端序）
    		rootcert_data1[0] = (PACKET_HEADER >> 8) & 0xFF;  // 0xEF
    		rootcert_data1[1] = PACKET_HEADER & 0xFF;         // 0x01
        	PRINTF("tlv->value: ");
        	for (int i=0; i<tlv->size; i++) {
        	    PRINTF("%02X \n", tlv->value[i]);
        	}
        	PRINTF("\r\n");
        	memcpy(&rootcert_data1[2], tlv->value, tlv->size);
        	uint16_t crc1 = NV_ComputeCrc(rootcert_data1, 860); // 假设CRC为0x1234
        	uint16_t reversed_crc = ((crc1 & 0xFF) << 8) | ((crc1 >> 8) & 0xFF); // 反转字节：0x1234 → 0x3412
        	PRINTF("reversed_crc = 0x%04X\r\n", reversed_crc);
        	memcpy(&rootcert_data1[860], &reversed_crc, 2);
        	PRINTF("rootcert_data1: ");
        	for (int i=0; i<864; i++) {
        	    PRINTF("%02X \n", rootcert_data1[i]);
        	}
        	PRINTF("\r\n");
        	memset(&s_buff[256], 0xFF, 864);
        	AES_128_ECB_Encrypt(rootcert_data1,864,AES_Key,rootcertdata_tlv);
        	PRINTF("rootcertdata_tlv: ");
        	for (int i=0; i<864; i++) {
        	    PRINTF("%02X \n", rootcertdata_tlv[i]);
        	}
        	PRINTF("\r\n");
        	memcpy(&s_buff[256], &rootcertdata_tlv, 864);

    		status = HAL_FlashEraseSector(startAdrss, PLATFORM_INTFLASH_SECTOR_SIZE);
    		if (kStatus_HAL_Flash_Success == status)
    		{
    			HAL_FlashProgram(startAdrss,PLATFORM_INTFLASH_SECTOR_SIZE,(uint8_t*)s_buff);
    			PRINTF("HAL_FlashProgram\r\n");
    			mTlvBuf[0] = ROOT_CACERT;
    			mTlvBuf[1] = 0x03;
    			mTlvBuf[2] = 0x02;
        		mTlvBuf[3] = ( crc1 >> 8) & 0xFF;
        		mTlvBuf[4] = crc1 & 0xFF;
        		UWB_Hif_SendRsp(mTlvBuf, 5);
    		}
    	//}
    	else
    	{
			mTlvBuf[0] = 0x05;
			mTlvBuf[1] = 0x01;
			mTlvBuf[2] = 0x01;
    		mTlvBuf[3] = 0xFF;
    		mTlvBuf[4] = 0xFF;
    		UWB_Hif_SendRsp(mTlvBuf, 5);
    	}
    	}
    }break;
    case LOCK_CERT:{
    	hal_flash_status_t status = 0;
    	memset(s_buff, 0xFF, PLATFORM_INTFLASH_SECTOR_SIZE);
    	status = HAL_FlashVerifyErase(LOCK_CERT_Adrss, 0x360u, kHAL_Flash_MarginValueNormal);
    	memset(lockcert_data, 0xFF, 864);
    	// 设置包头（大端序）
    	lockcert_data[0] = (PACKET_HEADER >> 8) & 0xFF;  // 0xEF
    	lockcert_data[1] = PACKET_HEADER & 0xFF;         // 0x01

    	if(status == kStatus_HAL_Flash_Success && tlv->size <= (sizeof(lockcert_data) - 4))
    	{
    		memcpy(&lockcert_data[2], tlv->value, tlv->size);
    		uint16_t  crc = NV_ComputeCrc(lockcert_data,860);
    		PRINTF("NV_ComputeCrc = %04X\r\n",crc);
    		lockcert_data[860] = ( crc >> 8) & 0xFF;
    		lockcert_data[861] = crc & 0xFF;
    		AES_128_ECB_Encrypt(lockcert_data,864,AES_Key,lockcert_data_encrypt);
    		HAL_FlashProgram(LOCK_CERT_Adrss,864,lockcert_data_encrypt);

    		mTlvBuf[0] = LOCK_CERT;
    		mTlvBuf[1] = 0x03;
    		mTlvBuf[2] = 0x01;
    		mTlvBuf[3] = ( crc >> 8) & 0xFF;
    		mTlvBuf[4] = crc & 0xFF;
    		UWB_Hif_SendRsp(mTlvBuf, 5);
    	}
    	else if(tlv->size <= (sizeof(lockcert_data) - 4))
    	{
    	for(uint32_t i = 0;i<IFR_SIZE;i++)
    	{
    		s_buff[i] = *(volatile uint32_t *)(startAdrss + i * 4);
    	}
    	memset(lockcertdata_sbf, 0xFF, 864);
    	memset(lockcertdata_sbfdecrypt, 0xFF, 864);
    	memcpy(lockcertdata_sbf, &s_buff[472], 864);
    	AES_128_ECB_Decrypt(lockcertdata_sbf,864,AES_Key,lockcertdata_sbfdecrypt);
    	//PRINTF("lockcertdata_sbfdecrypt: ");
    	//for (int i=0; i<864; i++) {
    	//    PRINTF("%02X \n", lockcertdata_sbfdecrypt[i]);
    	//}
    	//PRINTF("\r\n");
    	memset(lockcert_data1, 0xFF, 864);

    	uint16_t crc_cpt = NV_ComputeCrc(lockcertdata_sbfdecrypt,860);
    	PRINTF("crc_cpt = %04X\r\n",crc_cpt);

    	//PRINTF("lockcertdata_sbfdecrypt[860] = %02X\r\n",lockcertdata_sbfdecrypt[860]);
    	//PRINTF("lockcertdata_sbfdecrypt[861] = %02X\r\n",lockcertdata_sbfdecrypt[861]);
    	uint16_t combined = ( (uint16_t)lockcertdata_sbfdecrypt[860] << 8 ) | (uint16_t)lockcertdata_sbfdecrypt[861];
    	PRINTF("combined = %04X\r\n",combined);
    	//if(crc_cpt == combined)
    	//{
    		//构造需要写入的加密数据包
        	// 设置包头（大端序）
    		lockcert_data1[0] = (PACKET_HEADER >> 8) & 0xFF;  // 0xEF
    		lockcert_data1[1] = PACKET_HEADER & 0xFF;         // 0x01
        	PRINTF("tlv->value: ");
        	for (int i=0; i<tlv->size; i++) {
        	    PRINTF("%02X \n", tlv->value[i]);
        	}
        	PRINTF("\r\n");
        	memcpy(&lockcert_data1[2], tlv->value, tlv->size);
        	uint16_t crc1 = NV_ComputeCrc(lockcert_data1, 860); // 假设CRC为0x1234
        	uint16_t reversed_crc = ((crc1 & 0xFF) << 8) | ((crc1 >> 8) & 0xFF); // 反转字节：0x1234 → 0x3412
        	PRINTF("reversed_crc = 0x%04X\r\n", reversed_crc);
        	memcpy(&lockcert_data1[860], &reversed_crc, 2);
        	PRINTF("lockcert_data1: ");
        	for (int i=0; i<864; i++) {
        	    PRINTF("%02X \n", lockcert_data1[i]);
        	}
        	PRINTF("\r\n");
        	memset(&s_buff[472], 0xFF, 864);
        	AES_128_ECB_Encrypt(lockcert_data1,864,AES_Key,lockcertdata_tlv);
        	PRINTF("lockcertdata_tlv: ");
        	for (int i=0; i<864; i++) {
        	    PRINTF("%02X \n", lockcertdata_tlv[i]);
        	}
        	PRINTF("\r\n");
        	memcpy(&s_buff[472], &lockcertdata_tlv, 864);

    		status = HAL_FlashEraseSector(startAdrss, PLATFORM_INTFLASH_SECTOR_SIZE);
    		if (kStatus_HAL_Flash_Success == status)
    		{
    			HAL_FlashProgram(startAdrss,PLATFORM_INTFLASH_SECTOR_SIZE,(uint8_t*)s_buff);
    			PRINTF("HAL_FlashProgram\r\n");
    			mTlvBuf[0] = LOCK_CERT;
    			mTlvBuf[1] = 0x03;
    			mTlvBuf[2] = 0x02;
        		mTlvBuf[3] = ( crc1 >> 8) & 0xFF;
        		mTlvBuf[4] = crc1 & 0xFF;
        		UWB_Hif_SendRsp(mTlvBuf, 5);
    		}
    	//}
    	else
    	{
			mTlvBuf[0] = 0x05;
			mTlvBuf[1] = 0x01;
			mTlvBuf[2] = 0x01;
    		mTlvBuf[3] = 0xFF;
    		mTlvBuf[4] = 0xFF;
    		UWB_Hif_SendRsp(mTlvBuf, 5);
    	}
    	}
    }break;
    case LOCK_KEY:{
    	hal_flash_status_t status = 0;
    	memset(s_buff, 0xFF, PLATFORM_INTFLASH_SECTOR_SIZE);
    	status = HAL_FlashVerifyErase(LOCK_KEY_Adrss, 0x100u, kHAL_Flash_MarginValueNormal);
    	memset(lockkey_data, 0xFF, 256);
    	// 设置包头（大端序）
    	lockkey_data[0] = (PACKET_HEADER >> 8) & 0xFF;  // 0xEF
    	lockkey_data[1] = PACKET_HEADER & 0xFF;         // 0x01

    	if(status == kStatus_HAL_Flash_Success && tlv->size <= (sizeof(lockkey_data) - 4))
    	{
    		memcpy(&lockkey_data[2], tlv->value, tlv->size);
    		uint16_t  crc = NV_ComputeCrc(lockkey_data,252);
    		PRINTF("NV_ComputeCrc = %04X\r\n",crc);
    		lockkey_data[252] = ( crc >> 8) & 0xFF;
    		lockkey_data[253] = crc & 0xFF;
    		AES_128_ECB_Encrypt(lockkey_data,256,AES_Key,lockkey_data_encrypt);
    		HAL_FlashProgram(LOCK_KEY_Adrss,256,lockkey_data_encrypt);

    		mTlvBuf[0] = LOCK_KEY;
    		mTlvBuf[1] = 0x03;
    		mTlvBuf[2] = 0x01;
    		mTlvBuf[3] = ( crc >> 8) & 0xFF;
    		mTlvBuf[4] = crc & 0xFF;
    		UWB_Hif_SendRsp(mTlvBuf, 5);
    	}
    	else if(tlv->size <= (sizeof(lockkey_data) - 4))
    	{
    	for(uint32_t i = 0;i<IFR_SIZE;i++)
    	{
    		s_buff[i] = *(volatile uint32_t *)(startAdrss + i * 4);
    	}
    	memset(lockkeydata_sbf, 0xFF, 256);
    	memset(lockkeydata_sbfdecrypt, 0xFF, 256);
    	memcpy(lockkeydata_sbf, &s_buff[688], 256);
    	AES_128_ECB_Decrypt(lockkeydata_sbf,256,AES_Key,lockkeydata_sbfdecrypt);
    	//PRINTF("lockkeydata_sbfdecrypt: ");
    	//for (int i=0; i<864; i++) {
    	//    PRINTF("%02X \n", lockkeydata_sbfdecrypt[i]);
    	//}
    	//PRINTF("\r\n");
    	memset(lockkey_data1, 0xFF, 256);

    	uint16_t crc_cpt = NV_ComputeCrc(lockkeydata_sbfdecrypt,252);
    	PRINTF("crc_cpt = %04X\r\n",crc_cpt);

    	uint16_t combined = ( (uint16_t)lockkeydata_sbfdecrypt[252] << 8 ) | (uint16_t)lockkeydata_sbfdecrypt[253];
    	PRINTF("combined = %04X\r\n",combined);
    	//if(crc_cpt == combined)
    	//{
    		//构造需要写入的加密数据包
        	// 设置包头（大端序）
    		lockkey_data1[0] = (PACKET_HEADER >> 8) & 0xFF;  // 0xEF
    		lockkey_data1[1] = PACKET_HEADER & 0xFF;         // 0x01
        	PRINTF("tlv->value: ");
        	for (int i=0; i<tlv->size; i++) {
        	    PRINTF("%02X \n", tlv->value[i]);
        	}
        	PRINTF("\r\n");
        	memcpy(&lockkey_data1[2], tlv->value, tlv->size);
        	uint16_t crc1 = NV_ComputeCrc(lockkey_data1, 252); // 假设CRC为0x1234
        	uint16_t reversed_crc = ((crc1 & 0xFF) << 8) | ((crc1 >> 8) & 0xFF); // 反转字节：0x1234 → 0x3412
        	PRINTF("reversed_crc = 0x%04X\r\n", reversed_crc);
        	memcpy(&lockkey_data1[252], &reversed_crc, 2);
        	PRINTF("lockkey_data1: ");
        	for (int i=0; i<256; i++) {
        	    PRINTF("%02X \n", lockkey_data1[i]);
        	}
        	PRINTF("\r\n");
        	memset(&s_buff[688], 0xFF, 256);
        	AES_128_ECB_Encrypt(lockkey_data1,864,AES_Key,lockkeydata_tlv);
        	PRINTF("lockkeydata_tlv: ");
        	for (int i=0; i<256; i++) {
        	    PRINTF("%02X \n", lockkeydata_tlv[i]);
        	}
        	PRINTF("\r\n");
        	memcpy(&s_buff[688], &lockkeydata_tlv, 256);

    		status = HAL_FlashEraseSector(startAdrss, PLATFORM_INTFLASH_SECTOR_SIZE);
    		if (kStatus_HAL_Flash_Success == status)
    		{
    			HAL_FlashProgram(startAdrss,PLATFORM_INTFLASH_SECTOR_SIZE,(uint8_t*)s_buff);
    			PRINTF("HAL_FlashProgram\r\n");
    			mTlvBuf[0] = LOCK_KEY;
    			mTlvBuf[1] = 0x03;
    			mTlvBuf[2] = 0x02;
        		mTlvBuf[3] = ( crc1 >> 8) & 0xFF;
        		mTlvBuf[4] = crc1 & 0xFF;
        		UWB_Hif_SendRsp(mTlvBuf, 5);
    		}
    	//}
    	else
    	{
			mTlvBuf[0] = 0x05;
			mTlvBuf[1] = 0x01;
			mTlvBuf[2] = 0x01;
    		mTlvBuf[3] = 0xFF;
    		mTlvBuf[4] = 0xFF;
    		UWB_Hif_SendRsp(mTlvBuf, 5);
    	}
    	}
    }break;
    case BLE_BROADCAST_KEY:{
    	hal_flash_status_t status = 0;
    	memset(s_buff, 0xFF, PLATFORM_INTFLASH_SECTOR_SIZE);
    	status = HAL_FlashVerifyErase(BLE_BROADCAST_KEY_Adrss, 0x40u, kHAL_Flash_MarginValueNormal);
    	uint8_t blebroadcastkey_data[64] = {0};
    	memset(blebroadcastkey_data, 0xFF, 64);
    	// 设置包头（大端序）
    	blebroadcastkey_data[0] = (PACKET_HEADER >> 8) & 0xFF;  // 0xEF
    	blebroadcastkey_data[1] = PACKET_HEADER & 0xFF;         // 0x01

    	if(status == kStatus_HAL_Flash_Success && tlv->size <= (sizeof(blebroadcastkey_data) - 4))
    	{
    		memcpy(&blebroadcastkey_data[2], tlv->value, tlv->size);
    		uint16_t  crc = NV_ComputeCrc(blebroadcastkey_data,60);
    		uint8_t  blebroadcastkeydata_encrypt[64] = {0};
    		PRINTF("NV_ComputeCrc = %04X\r\n",crc);
    		blebroadcastkey_data[60] = ( crc >> 8) & 0xFF;
    		blebroadcastkey_data[61] = crc & 0xFF;
    		AES_128_ECB_Encrypt(blebroadcastkey_data,64,AES_Key,blebroadcastkeydata_encrypt);
    		HAL_FlashProgram(BLE_BROADCAST_KEY_Adrss,64,blebroadcastkeydata_encrypt);

    		mTlvBuf[0] = BLE_BROADCAST_KEY;
    		mTlvBuf[1] = 0x03;
    		mTlvBuf[2] = 0x01;
    		mTlvBuf[3] = ( crc >> 8) & 0xFF;
    		mTlvBuf[4] = crc & 0xFF;
    		UWB_Hif_SendRsp(mTlvBuf, 5);
    	}
    	else if(tlv->size <= (sizeof(blebroadcastkey_data) - 4))
    	{
    	for(uint32_t i = 0;i<IFR_SIZE;i++)
    	{
    		s_buff[i] = *(volatile uint32_t *)(startAdrss + i * 4);
    	}
    	uint8_t blebroadcastdata_sbf[64] = {0};
    	uint8_t blebroadcastdata_sbfdecrypt[64] = {0};//用于存放flash中解密后的qrcode_data
    	memset(blebroadcastdata_sbf, 0xFF, 64);
    	memset(blebroadcastdata_sbfdecrypt, 0xFF, 64);
    	memcpy(blebroadcastdata_sbf, &s_buff[752], 64);
    	AES_128_ECB_Decrypt(blebroadcastdata_sbf,64,AES_Key,blebroadcastdata_sbfdecrypt);
    	PRINTF("blebroadcastdata_sbfdecrypt: ");
    	for (int i=0; i<64; i++) {
    	    PRINTF("%02X \n", blebroadcastdata_sbfdecrypt[i]);
    	}
    	PRINTF("\r\n");
    	uint8_t blebroadcast_data1[64] = {0}; //用于存放发送的blebroadcast_data1
    	memset(blebroadcast_data1, 0xFF, 64);
    	uint8_t broadcastdata_tlv[64] = {0}; //用于存放加密后的blebroadcast_data1

    	uint16_t crc_cpt = NV_ComputeCrc(blebroadcastdata_sbfdecrypt,60);
    	PRINTF("crc_cpt = %04X\r\n",crc_cpt);

    	uint16_t combined = ( (uint16_t)blebroadcastdata_sbfdecrypt[60] << 8 ) | (uint16_t)blebroadcastdata_sbfdecrypt[61];
    	PRINTF("combined = %04X\r\n",combined);
    	//if(crc_cpt == combined)
    	//{
    		//构造需要写入的加密数据包
        	// 设置包头（大端序）
    		blebroadcast_data1[0] = (PACKET_HEADER >> 8) & 0xFF;  // 0xEF
    		blebroadcast_data1[1] = PACKET_HEADER & 0xFF;         // 0x01
        	PRINTF("tlv->value: ");
        	for (int i=0; i<tlv->size; i++) {
        	    PRINTF("%02X \n", tlv->value[i]);
        	}
        	PRINTF("\r\n");
        	memcpy(&blebroadcast_data1[2], tlv->value, tlv->size);
        	uint16_t crc1 = NV_ComputeCrc(blebroadcast_data1, 60); // 假设CRC为0x1234
        	uint16_t reversed_crc = ((crc1 & 0xFF) << 8) | ((crc1 >> 8) & 0xFF); // 反转字节：0x1234 → 0x3412
        	PRINTF("reversed_crc = 0x%04X\r\n", reversed_crc);
        	memcpy(&blebroadcast_data1[60], &reversed_crc, 2);
        	PRINTF("broadcastdata_data1: ");
        	for (int i=0; i<64; i++) {
        	    PRINTF("%02X \n", blebroadcast_data1[i]);
        	}
        	PRINTF("\r\n");
        	memset(&s_buff[752], 0xFF, 64);
        	AES_128_ECB_Encrypt(blebroadcast_data1,64,AES_Key,broadcastdata_tlv);
        	PRINTF("broadcastdata_tlv: ");
        	for (int i=0; i<64; i++) {
        	    PRINTF("%02X \n", broadcastdata_tlv[i]);
        	}
        	PRINTF("\r\n");
        	memcpy(&s_buff[752], &broadcastdata_tlv, 64);

    		status = HAL_FlashEraseSector(startAdrss, PLATFORM_INTFLASH_SECTOR_SIZE);
    		if (kStatus_HAL_Flash_Success == status)
    		{
    			HAL_FlashProgram(startAdrss,PLATFORM_INTFLASH_SECTOR_SIZE,(uint8_t*)s_buff);
    			PRINTF("HAL_FlashProgram\r\n");
    			mTlvBuf[0] = BLE_BROADCAST_KEY;
    			mTlvBuf[1] = 0x03;
    			mTlvBuf[2] = 0x02;
        		mTlvBuf[3] = ( crc1 >> 8) & 0xFF;
        		mTlvBuf[4] = crc1 & 0xFF;
        		UWB_Hif_SendRsp(mTlvBuf, 5);
    		}
    	//}
    	else
    	{
			mTlvBuf[0] = 0x05;
			mTlvBuf[1] = 0x01;
			mTlvBuf[2] = 0x01;
    		mTlvBuf[3] = 0xFF;
    		mTlvBuf[4] = 0xFF;
    		UWB_Hif_SendRsp(mTlvBuf, 5);
    	}
    	}
    }break;
    case OTA_REQUEST_START_CMD:{
        otaResult_t result = 0;


    	if (tlv->size == 4u) {
    		g_ota_file_len = (tlv->value[0] << 24u) | (tlv->value[1] << 16)
    				| (tlv->value[2] << 8u) | (tlv->value[3]);
    		PRINTF("g_ota_file_len : %d \n", g_ota_file_len);
    	} else {
    		PRINTF("recv OTA_REQUEST_START_CMD error\r\n");
    		UWB_Respond_cmd(OTA_RESPONSE_START_CMD, gOtaInvalidParam_c);
    		return;
    	}
    	OtaInit();

        OTA_StartImage(g_ota_file_len);
        result = OTA_MakeHeadRoomForNextBlock(g_ota_file_len, NULL, 0);

        if (result != gOtaSuccess_c) {
        	PRINTF("OTA_REQUEST_START_CMD error \r\n");
        	uwb_ota_init = 0;
        	UWB_Respond_cmd(OTA_RESPONSE_START_CMD, gOtaExternalFlashError_c);
        } else {
        	uwb_ota_init = 1;
        	PRINTF("OTA_REQUEST_START_CMD SUCCESS \r\n");
        	UWB_Respond_cmd(OTA_RESPONSE_START_CMD, gOtaSuccess_c);
        }
    }break;

    case OTA_DATA_SEND_CMD:{
    	otaResult_t result = 0;
    	uint8_t i = 0u;
    	uint16_t otaCRC = 0u;
    	uint16_t otaUartCRC = 0u;
    	static int i_ota_count = 0;
    	if ((tlv->size <= 2) && (uwb_ota_init != 1) && (tlv->size > 258)) {
    		vTaskDelay(2);
    		PRINTF("OTA_DATA_SEND_CMD error param \r\n");
    		UWB_Respond_cmd(OTA_DATA_RESPOND_CMD, gOtaInvalidParam_c);
    		return;
    	}
    	//如果失败，重新写入三次查看是否成功
    	otaCRC = NV_ComputeCrc(tlv->value, (tlv->size - 2));
    	otaUartCRC = (tlv->value[tlv->size-2] << 8u) | (tlv->value[tlv->size-1]);

    	//PRINTF("otaCRC: 0x%04x \r\n", otaCRC);
    	//PRINTF("otaUartCRC: 0x%04x \r\n", otaUartCRC);
    	PRINTF("CRC: otaUartCRC 0x%04x \r\n", otaUartCRC);
    	if (otaCRC != otaUartCRC) {
    		PRINTF("OTA_DATA_SEND_CMD CRC error \r\n");
    		vTaskDelay(2);
    		UWB_Respond_cmd(OTA_DATA_RESPOND_CMD, gOtaCrcError_c);
    		return;
    	}

		result = OTA_PushImageChunk(tlv->value, (tlv->size - 2), NULL, NULL);

		//FLib_MemSet(tlv->value, 0 , 258);
		if (result != gOtaSuccess_c) {
			PRINTF("OTA_PushImageChunk error result:%d \r\n", result);
			UWB_Respond_cmd(OTA_DATA_RESPOND_CMD, gOtaExternalFlashError_c);
		} else {
			PRINTF("ota successful %d \r\n", i_ota_count);
			i_ota_count++;
			UWB_Respond_cmd(OTA_DATA_RESPOND_CMD, gOtaSuccess_c);
		}

		//vTaskDelay(2);//note by cgyuan
		//UWB_Respond_cmd(OTA_DATA_RESPOND_CMD, result);

    }break;

    case OTA_DATA_SEND_FINISH_CMD:{
    	otaResult_t result = 0;

    	if ((tlv->size != 2) && (uwb_ota_init != 1)) {
    		PRINTF("OTA_DATA_SEND_FINISH_CMD PARAM error \r\n");
    		UWB_Respond_cmd(OTA_DATA_RESPONSE_FINESH_CMD, gOtaInvalidParam_c);
    		return;
    	}
    	if (mOtaHdl.OtaImageCurrentLength == g_ota_file_len) {
    		PRINTF("OTA FINISTH SUCCESS \r\n");
    		result = gOtaSuccess_c;
    		uwb_ota_init = 0;
    	} else {
    		PRINTF("OTA FINISTH gOtaImageInvalid_c error \r\n");
    		result = gOtaImageInvalid_c;
    	}

    	UWB_Respond_cmd(OTA_DATA_RESPONSE_FINESH_CMD, result);
    }break;

    case OTA_SET_BOOT_INFO_CMD:{
    	otaResult_t result = 0;

    	if (tlv->size != 4)
    	{
    		PRINTF("OTA_SET_BOOT_INFO_CMD error tlv->size:%d \r\n", tlv->size);
    		UWB_Respond_cmd(OTA_RESPONSE_BOOT_INFO_CMD, gOtaInvalidParam_c);
    		return;
    	}

		g_ota_file_len = (tlv->value[0] << 24u) | (tlv->value[1] << 16)
				| (tlv->value[2] << 8u) | (tlv->value[3]);

		OTA_UpdateNewImageFlag(g_ota_file_len);

		if (mOtaHdl.FwUpdImageState == OtaImgState_Fail){
			PRINTF("Error  OTA_UpdateNewImageFlag \r\n");
    		UWB_Respond_cmd(OTA_RESPONSE_BOOT_INFO_CMD, gOtaImageInvalid_c);
    		return;
		}
		PRINTF("OTA_SET_BOOT_INFO_CMD SUCCESSFUL\r\n");
		UWB_Respond_cmd(OTA_RESPONSE_BOOT_INFO_CMD, gOtaSuccess_c);
		vTaskDelay(2);
		HAL_ResetMCU();
    }break;

    case OTA_GET_FIRMWARE_VERSION:{
    	otaResult_t result = 0;
    	if ((tlv->size != 1) && (tlv->value[0] != 0x01))
    	{
    		UWB_Respond_cmd(OTA_RESPONSE_FIRMWARE_VERSION, gOtaInvalidParam_c);
    		return;
    	}

    	UWB_Respond_cmd(OTA_RESPONSE_FIRMWARE_VERSION, 0x02);
    }break;

    case EXTERNAL_FLASH_TEST_CMD:{
    	status_t st = kStatus_Fail;
    	uint32_t address = PLATFORM_EXTFLASH_TOTAL_SIZE - PLATFORM_EXTFLASH_SECTOR_SIZE;

    	if ((tlv->size != 1) && (tlv->value[0] != 0x01))
    	{
    		UWB_Respond_cmd(EXTERNAL_FLASH_RESPONSE_TEST_CMD, gFlashParamInvalid_c);
    		return;
    	}


    	FLib_MemSet(flash_buf, 0xff, PLATFORM_EXTFLASH_PAGE_SIZE);

    	flash_buf[0] = 0x01;
    	flash_buf[1] = 0x02;
    	flash_buf[2] = 0x03;
    	flash_buf[3] = 0x04;
    	st = PLATFORM_InitExternalFlash();
    	if (st != kStatus_Success) {
    		PRINTF("PLATFORM_InitExternalFlash error \r\n");
    		UWB_Respond_cmd(EXTERNAL_FLASH_RESPONSE_TEST_CMD, gFlashInitError_c);
    		return;
    	}

    	st = PLATFORM_EraseExternalFlash(address, PLATFORM_EXTFLASH_SECTOR_SIZE);
    	if (st != kStatus_Success) {
    		PRINTF("PLATFORM_EraseExternalFlash error \r\n");
    		UWB_Respond_cmd(EXTERNAL_FLASH_RESPONSE_TEST_CMD, gFlashEraseError_c);
    		return;
    	}

    	st = PLATFORM_WriteExternalFlash(flash_buf, PLATFORM_EXTFLASH_PAGE_SIZE, address);
    	if (st != kStatus_Success) {
    		PRINTF("PLATFORM_WriteExternalFlash error \r\n");
    		UWB_Respond_cmd(EXTERNAL_FLASH_RESPONSE_TEST_CMD, gFlashWriteError_c);
    		return;
    	}

    	FLib_MemSet(flash_buf, 0xff, PLATFORM_EXTFLASH_PAGE_SIZE);
    	st = PLATFORM_ReadExternalFlash(flash_buf, PLATFORM_EXTFLASH_PAGE_SIZE, address, TRUE);
    	if (st != kStatus_Success) {
    		PRINTF("PLATFORM_ReadExternalFlash error \r\n");
    		UWB_Respond_cmd(EXTERNAL_FLASH_RESPONSE_TEST_CMD, gFlashReadError_c);
    		return;
    	}

    	if ((flash_buf[0] != 0x01) || (flash_buf[1] != 0x02) ||
    		(flash_buf[2] != 0x03) || (flash_buf[3] != 0x04)) {

    		PRINTF("external flash verify error \r\n");
    		UWB_Respond_cmd(EXTERNAL_FLASH_RESPONSE_TEST_CMD, gFlashVerifyError_c);
    		return;
    	}
    	st = PLATFORM_EraseExternalFlash(address, PLATFORM_EXTFLASH_SECTOR_SIZE);
    	if (st != kStatus_Success) {
    		PRINTF("PLATFORM_EraseExternalFlash 2 error \r\n");
    		UWB_Respond_cmd(EXTERNAL_FLASH_RESPONSE_TEST_CMD, gFlashEraseError_c);
    		return;
    	}

    	UWB_Respond_cmd(EXTERNAL_FLASH_RESPONSE_TEST_CMD, gFlashSuccess_c);

    }break;

    case INTERNAL_FLASH_TEST_CMD:{
    	hal_flash_status_t status;
    	uint32_t address = FSL_FEATURE_FLASH_PFLASH_BLOCK_SIZE - FSL_FEATURE_FLASH_PFLASH_SECTOR_SIZE;

    	if ((tlv->size != 1) && (tlv->value[0] != 0x01))
    	{
    		UWB_Respond_cmd(INTERNAL_FLASH_RESPONSE_TEST_CMD, gFlashParamInvalid_c);
    		return;
    	}
    	status = HAL_FlashInit();
    	if (status != kStatus_HAL_Flash_Success) {
    		PRINTF("HAL_FlashInit error \r\n");
    		UWB_Respond_cmd(INTERNAL_FLASH_RESPONSE_TEST_CMD, gFlashInitError_c);
    		return;
    	}
    	status = HAL_FlashEraseSector(address, FSL_FEATURE_FLASH_PFLASH_PHRASE_SIZE);
    	if (status != kStatus_HAL_Flash_Success) {
    		PRINTF("HAL_FlashEraseSector error \r\n");
    		UWB_Respond_cmd(INTERNAL_FLASH_RESPONSE_TEST_CMD, gFlashEraseError_c);
    		return;
    	}
    	FLib_MemSet(flash_buf, 0xff, PLATFORM_EXTFLASH_PAGE_SIZE);
    	flash_buf[0] = 0x01;
    	flash_buf[1] = 0x02;
    	flash_buf[2] = 0x03;
    	flash_buf[3] = 0x04;
        status = HAL_FlashProgram(address, FSL_FEATURE_FLASH_PFLASH_PHRASE_SIZE, flash_buf);
    	if (status != kStatus_HAL_Flash_Success) {
    		PRINTF("HAL_FlashProgram error \r\n");
    		UWB_Respond_cmd(INTERNAL_FLASH_RESPONSE_TEST_CMD, gFlashWriteError_c);
    		return;
    	}

    	FLib_MemSet(flash_buf, 0xff, PLATFORM_EXTFLASH_PAGE_SIZE);
    	status = HAL_FlashRead(address, FSL_FEATURE_FLASH_PFLASH_PHRASE_SIZE, flash_buf);
    	if ((flash_buf[0] != 0x01) || (flash_buf[1] != 0x02) ||
    		(flash_buf[2] != 0x03) || (flash_buf[3] != 0x04)) {
    		PRINTF("flash verify error \r\n");
    		UWB_Respond_cmd(INTERNAL_FLASH_RESPONSE_TEST_CMD, gFlashVerifyError_c);
    		return;
    	}

    	status = HAL_FlashEraseSector(address, FSL_FEATURE_FLASH_PFLASH_PHRASE_SIZE);
    	if (status != kStatus_HAL_Flash_Success) {
    		PRINTF("HAL_FlashEraseSector 2 error \r\n");
    		UWB_Respond_cmd(INTERNAL_FLASH_RESPONSE_TEST_CMD, gFlashEraseError_c);
    		return;
    	}

    	UWB_Respond_cmd(INTERNAL_FLASH_RESPONSE_TEST_CMD, gFlashSuccess_c);

    }break;

    case MCU_LOWPOWER:{
        uint32_t freq;
        cmc_low_power_mode_t curmode;

    	APP_SetCMCConfiguration();
        APP_DeInitVbat();

        freq    = CLOCK_GetFreq(kCLOCK_CoreSysClk);
        curmode = CMC_GetMAINPowerMode(APP_CMC);

		mTlvBuf[0] = 0x08;
		mTlvBuf[1] = 0x00;
		mTlvBuf[2] = 0x00;
		mTlvBuf[3] = 0xFF;
		mTlvBuf[4] = 0xFF;
		UWB_Hif_SendRsp(mTlvBuf, 5);
        APP_EnterDeepSleep1Mode();

    }break;
    case HPD_MODE:{
    		mTlvBuf[0] = 0x09;
    		mTlvBuf[1] = 0x00;
    		mTlvBuf[2] = 0x00;
    		mTlvBuf[3] = 0xFF;
    		mTlvBuf[4] = 0xFF;
    		UWB_Hif_SendRsp(mTlvBuf, 5);
        	GPIO_PinWrite(BOARD_INITUWBPINS_UWB_CHIPENABLE_GPIO,  // GPIO端口（对应PTC的基地址）
        	              BOARD_INITUWBPINS_UWB_CHIPENABLE_PIN,   // 引脚号（对应5）
        	              0U);                                    // 输出0U表示拉低
        }break;
    case REBOOT:{
		mTlvBuf[0] = 0x0A;
		mTlvBuf[1] = 0x00;
		mTlvBuf[2] = 0x00;
		mTlvBuf[3] = 0xFF;
		mTlvBuf[4] = 0xFF;
		UWB_Hif_SendRsp(mTlvBuf, 5);

		NVIC_SystemReset();
    }break;
    case IFR_ERASE:{
    	hal_flash_status_t status;
    	status = HAL_FlashEraseSector(startAdrss, PLATFORM_INTFLASH_SECTOR_SIZE);
    	if(status == kStatus_HAL_Flash_Success)
    	{
    		mTlvBuf[0] = 0x0B;
    		mTlvBuf[1] = 0x00;
    		mTlvBuf[2] = 0x00;
    		mTlvBuf[3] = 0xFF;
    		mTlvBuf[4] = 0xFF;
    		UWB_Hif_SendRsp(mTlvBuf, 5);
    	}
    	else
    	{
    		mTlvBuf[0] = 0x05;
    		mTlvBuf[1] = 0x01;
    		mTlvBuf[2] = 0x01;
    		mTlvBuf[3] = 0xFF;
    		mTlvBuf[4] = 0xFF;
    		UWB_Hif_SendRsp(mTlvBuf, 5);
    	}
    }break;
    default:
        PRINTF("ERROR: invalid TLV type %02x\n", tlv->type);
    }
}

void AES_Key_Init()
{
	SecLib_Init();
	RNG_Init();

    uint8_t uid[16] = {0};
    uint8_t len = 0;
    PLATFORM_GetMCUUid (uid, &len);
    memcpy(uid_32bytes, uid, 16);  // 复制前16字节UID
#if 0
    PRINTF("uid_32bytes[32]:\n");
    for (int i = 0; i < 32; i++) {
        // 以两位十六进制格式打印，不足两位补0，每个字节后加空格分隔
    	PRINTF("%02X ", uid_32bytes[i]);
        // 每8个字节换行，方便阅读
        if ((i + 1) % 8 == 0) {
        	PRINTF("\r\n");
        }
    }
#endif

    RNG_SetExternalSeed(uid_32bytes);
    RNG_GetPseudoRandomData(AES_Key, 16, NULL);
#if 0
    PRINTF("AES_Key[16]:\n");
    for (int i = 0; i < 16; i++) {
        // 以两位十六进制格式打印，不足两位补0，每个字节后加空格分隔
    	PRINTF("%02X ", AES_Key[i]);
        // 每8个字节换行，方便阅读
        if ((i + 1) % 8 == 0) {
        	PRINTF("\n");
        }
    }
    PRINTF("\r\n"); // 最后换行
#endif
}

static void APP_SetSPCConfiguration(void)
{
    static volatile status_t status = kStatus_Success;

    /* Disable LVDs and HVDs in Active mode. */
    SPC_EnableActiveModeCoreHighVoltageDetect(APP_SPC, false);
    SPC_EnableActiveModeCoreLowVoltageDetect(APP_SPC, false);
    SPC_EnableActiveModeSystemHighVoltageDetect(APP_SPC, false);
    SPC_EnableActiveModeSystemLowVoltageDetect(APP_SPC, false);
    SPC_EnableActiveModeIOHighVoltageDetect(APP_SPC, false);
    SPC_EnableActiveModeIOLowVoltageDetect(APP_SPC, false);

    while (SPC_GetBusyStatusFlag(APP_SPC))
    {}

    spc_active_mode_regulators_config_t activeModeRegulatorOption;
    activeModeRegulatorOption.bandgapMode                      = kSPC_BandgapEnabledBufferDisabled;
    activeModeRegulatorOption.lpBuff                           = false;
    activeModeRegulatorOption.DCDCOption.DCDCVoltage           = kSPC_DCDC_NormalVoltage; /* DCDC regulate to 1.5V. */
    activeModeRegulatorOption.DCDCOption.DCDCDriveStrength     = kSPC_DCDC_NormalDriveStrength;
    activeModeRegulatorOption.SysLDOOption.SysLDOVoltage       = kSPC_SysLDO_NormalVoltage;
    activeModeRegulatorOption.SysLDOOption.SysLDODriveStrength = kSPC_SysLDO_NormalDriveStrength;
    activeModeRegulatorOption.CoreLDOOption.CoreLDOVoltage =
        kSPC_CoreLDO_NormalVoltage; /* Core LDO regulate to 1.1V. */
#if defined(FSL_FEATURE_SPC_HAS_CORELDO_VDD_DS) && FSL_FEATURE_SPC_HAS_CORELDO_VDD_DS
    activeModeRegulatorOption.CoreLDOOption.CoreLDODriveStrength = kSPC_CoreLDO_NormalDriveStrength;
#endif /* FSL_FEATURE_SPC_HAS_CORELDO_VDD_DS */
    if (SPC_SetActiveModeDCDCRegulatorConfig(APP_SPC, &activeModeRegulatorOption.DCDCOption) != kStatus_Success)
    {
        PRINTF("Fail to set DCDC in Active Mode!\r\n");
    }
    while (SPC_GetBusyStatusFlag(APP_SPC))
    {}
    if (SPC_SetActiveModeSystemLDORegulatorConfig(APP_SPC, &activeModeRegulatorOption.SysLDOOption) != kStatus_Success)
    {
        PRINTF("Fail to set System LDO in Active Mode!\r\n ");
    }
    if (SPC_SetActiveModeBandgapModeConfig(APP_SPC, activeModeRegulatorOption.bandgapMode) != kStatus_Success)
    {
        PRINTF("Fail to set bandgap mode in Active Mode!\r\n");
    }
    status = SPC_SetActiveModeCoreLDORegulatorConfig(APP_SPC, &activeModeRegulatorOption.CoreLDOOption);
    if (status != kStatus_Success)
    {
        PRINTF("Fail to set Core LDO in Active mode!\r\n");
    }
    SPC_EnableActiveModeCMPBandgapBuffer(APP_SPC, activeModeRegulatorOption.lpBuff);

    spc_lowpower_mode_regulators_config_t lowPowerRegulatorOption;

    lowPowerRegulatorOption.lpIREF                             = false;
    lowPowerRegulatorOption.bandgapMode                        = kSPC_BandgapDisabled;
    lowPowerRegulatorOption.lpBuff                             = false;
    lowPowerRegulatorOption.CoreIVS                            = false;
    lowPowerRegulatorOption.DCDCOption.DCDCVoltage             = kSPC_DCDC_LowUnderVoltage;
    lowPowerRegulatorOption.DCDCOption.DCDCDriveStrength       = kSPC_DCDC_LowDriveStrength;
    lowPowerRegulatorOption.SysLDOOption.SysLDODriveStrength   = kSPC_SysLDO_LowDriveStrength;
    lowPowerRegulatorOption.CoreLDOOption.CoreLDOVoltage       = kSPC_CoreLDO_MidDriveVoltage;
    lowPowerRegulatorOption.CoreLDOOption.CoreLDODriveStrength = kSPC_CoreLDO_LowDriveStrength;

    status = SPC_SetLowPowerModeRegulatorsConfig(APP_SPC, &lowPowerRegulatorOption);
    if (status != kStatus_Success)
    {
        PRINTF("Fail to set regulators in Low Power Mode.");
        return;
    }

    SPC_SetLowPowerWakeUpDelay(APP_SPC, 0xFFFFU);
}

int main(void)
{
    phOsalUwb_ThreadCreationParams_t threadParams;

    APP_SetSPCConfiguration();

    /* Init board hardware. */
    BOARD_InitHardware();

//    LED_Init();
//    GPIO_InitTimer();
    /* Override pin configurations with SWO, if in debug session */
    // BOARD_InitSwoPins();
//    CLOCK_AttachClk(BOARD_DEBUG_UART_CLK_ATTACH);
    /* DeInitialize UART Debug instance */
//    BOARD_DeinitDebugConsole();
    //DbgConsole_Deinit();
    /* Enable the SWO Debug consle for only in debug session */
//    if (IS_DEBUG_SESSION) {
//        BOARD_InitSwoDebugConsole();
//    }
    AES_Key_Init();

    PRINT_APP_NAME("Demo PNP Rhodes V4");


    PRINTF("this is test firmware ====================> V 2.00 Enter \r\n");
    PRINTF("this is test firmware ====================> V 2.00 Enter \r\n");
    PRINTF("this is test firmware ====================> V 2.00 Enter \r\n");
    /* Init Helios subsystem */
    UWB_Tml_Io_Init();

    /* Init Helios subsystem */
    if (kUWBSTATUS_SUCCESS == UWB_HeliosSpiInit()) {
        PRINTF_WITH_TIME("main(): Helios initialized\n");
    }
    else {
        PRINTF_WITH_TIME("CRITICAL: error initializing Helios\n");
        while (1)
            ;
    }


    PRINTF_WITH_TIME("main(): GPIO/IRQ module initialized\n");



    /* This mutex is used to make USB write operations(Bulkin) from Rhodes mutually exclusive . */
    if (phOsalUwb_CreateMutex(&mHifWriteMutex) != UWBSTATUS_SUCCESS) {
        PRINTF_WITH_TIME("Error: UWB_HeliosInit(), could not create mutex mUsbWriteMutex\n");
        while (1)
            ;
    }

    /* This mutex is used to make USB write operations(Bulkin) from Rhodes mutually exclusive . */
    if (phOsalUwb_CreateMutex(&mHifSyncMutex) != UWBSTATUS_SUCCESS) {
        PRINTF_WITH_TIME("Error: UWB_HeliosInit(), could not create mutex mUsbWriteMutex\n");
        while (1)
            ;
    }
    /* This mutex is used to make Reset operation and USB write operation from UWB_WriterTask mutually exclusive
     * anytime Host can send a Reset command when ranging is ongoing*/
    if (phOsalUwb_CreateMutex(&mUartWriteMutex) != UWBSTATUS_SUCCESS) {
        PRINTF_WITH_TIME("Error: UWB_HeliosInit(), could not create mutex mUsbSyncMutex\n");
        while (1)
            ;
    }
    /* This semaphore is signaled in the USB CDC ISR context when any command is received from Host*/
    if (phOsalUwb_CreateBinSem(&mHifIsr_Sem) != UWBSTATUS_SUCCESS) {
        PRINTF_WITH_TIME("Error: main, could not create semaphore mSem\n");
        while (1)
            ;
    }
    /* This Queue is used to store the notifications received from helios
     * Currently it can store WRITER_QUEUE_SIZE elements*/
    mHifWriteQueue = phOsalUwb_msgget(WRITER_QUEUE_SIZE);
    if (!mHifWriteQueue) {
        PRINTF_WITH_TIME("Error: main, could not create queue mUsbWriteQueue\n");
        while (1)
            ;
    }
    /* This Queue is used to store the commands received from Host
     * Currently it can store MAX 1 element at a time*/
    mHifCommandQueue = phOsalUwb_msgget(1);
    if (!mHifCommandQueue) {
        PRINTF_WITH_TIME("Error: main, could not create queue mHifCommandQueue\n");
        while (1)
            ;
    }

    threadParams.stackdepth = PNP_APP_TASK_SIZE;
    PHOSALUWB_SET_TASKNAME(threadParams, "UWB_Pnp_App_Task");
    threadParams.pContext = NULL;
    threadParams.priority = PNP_APP_TASK_PRIO;
    /*This is the PNP Rhodes Application task which receives all the commands sent by Host*/
    phOsalUwb_Thread_Create((void **)&mPnpAppTask, &UWB_Pnp_App_Task, &threadParams);

    threadParams.stackdepth = HIF_TASK_SIZE;
    PHOSALUWB_SET_TASKNAME(threadParams, "UWB_HIF_Task");
    threadParams.pContext = NULL;
    threadParams.priority = HIF_TASK_PRIO;
    /*This task is waiting on a CDC USB interrupt. Once USB command is received, it is forwarded to UWB_HeliosTask queue
     *for the further processing */
    phOsalUwb_Thread_Create((void **)&mHifTask, &UWB_Hif_Handler_Task, &threadParams);

    threadParams.stackdepth = UCI_READER_TASK_SIZE;
    PHOSALUWB_SET_TASKNAME(threadParams, "UCI_ReaderTask");
    threadParams.pContext = NULL;
    threadParams.priority = UCI_READER_TASK_PRIO;
    /*This task is used for reading UCI resp and notifications from Helios. its blocked on a helios IRQ interrupt*/
    phOsalUwb_Thread_Create((void **)&mUciReaderTask, &UCI_ReaderTask, &threadParams);

    threadParams.stackdepth = HIF_WRITER_TASK_SIZE;
    PHOSALUWB_SET_TASKNAME(threadParams, "UWB_WriterTask");
    threadParams.pContext = NULL;
    threadParams.priority = HIF_WRITER_TASK_PRIO;
    /*This task is used for sending all notifications received from helios to Host via CDC USB interface.*/
    phOsalUwb_Thread_Create((void **)&mHifWriterTask, &UWB_WriterTask, &threadParams);


    phOsalUwb_TaskStartScheduler();
    return 0;

}

#endif // UWBIOT_APP_BUILD__DEMO_PNP
